在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进行文件操作的基本方法和一些高级技巧,能够有效提高文件操作的效率和便捷性。