在Ubuntu系統中使用Python進行文件操作時,可以掌握以下技巧:
python --version
或 python3 --version
命令確認系統中的Python版本。~/.bashrc
文件并添加 export PATH=$PATH:/usr/bin/python3
來配置Python環境變量,確??梢允褂?python3
命令。讀取文件:
with open('example.txt', 'r') as file:
打開文件并讀取內容。for line in file:
。寫入文件:
with open('output.txt', 'w') as file: file.write("Hello, world!\n")
。with open('output.txt', 'a') as file: file.write("More text to append.\n")
。with open('output.txt', 'w') as file: file.writelines(lines)
。刪除文件:使用 os.remove('example.txt')
刪除文件。
檢查文件是否存在:import os; if os.path.exists('example.txt'): print("File exists!")
。
重命名文件:os.rename('old_name.txt', 'new_name.txt')
。
獲取文件大小:size = os.path.getsize('example.txt')
打印文件大小。
with open('image.png', 'rb') as file: image_data = file.read()
。data = b'\x00\x01\x02\x03' with open('binary_file.bin', 'wb') as file: file.write(data)
。遍歷目錄:使用 os.walk(directory_path)
遍歷目錄及其子目錄中的所有文件,并讀取每個文件的內容。
刪除目錄:
os.rmdir('empty_directory')
。shutil.rmtree('directory_to_delete')
。python 文件名.py
或 python3 文件名.py
命令運行Python腳本。chmod +x 文件名.py
后使用 ./文件名.py
運行。sudo ln -s /usr/bin/python3 /usr/bin/python
將 python
命令指向Python 3.x版本。以上技巧涵蓋了在Ubuntu系統中使用Python進行文件操作的基本方法和一些高級技巧,能夠有效提高文件操作的效率和便捷性。