在Ubuntu上使用Python进行文件操作,主要涉及以下几个步骤:
Python提供了多个内置模块来处理文件和目录操作,常用的有os
、shutil
和pathlib
。
os
模块:提供了一系列与操作系统交互的功能。shutil
模块:提供了高级文件操作,如复制、移动和删除文件。pathlib
模块:提供了一个面向对象的接口来处理文件系统路径。import os
import shutil
from pathlib import Path
使用open()
函数打开文件,并指定模式(如读、写、追加等)。
# 以读模式打开文件
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# 以写模式打开文件
with open('example.txt', 'w') as file:
file.write('Hello, World!')
# 以追加模式打开文件
with open('example.txt', 'a') as file:
file.write('\nAppended text.')
可以使用read()
、readline()
或readlines()
方法读取文件内容。
# 读取整个文件内容
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# 逐行读取文件内容
with open('example.txt', 'r') as file:
for line in file:
print(line, end='')
# 读取所有行并存储在列表中
with open('example.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line, end='')
使用write()
方法写入内容到文件。
with open('example.txt', 'w') as file:
file.write('New content')
使用with
语句可以自动关闭文件,确保资源被正确释放。
with open('example.txt', 'w') as file:
file.write('Content')
# 文件在此处自动关闭
使用os
和shutil
模块进行文件和目录操作。
os.makedirs('new_directory', exist_ok=True)
shutil.rmtree('new_directory')
shutil.copy('source.txt', 'destination.txt')
shutil.move('source.txt', 'destination.txt')
# 获取文件大小
file_size = os.path.getsize('example.txt')
print(f'File size: {file_size} bytes')
# 获取文件修改时间
modification_time = os.path.getmtime('example.txt')
print(f'Modification time: {modification_time}')
pathlib
模块pathlib
模块提供了一个更现代和面向对象的接口来处理文件系统路径。
# 创建路径对象
path = Path('example.txt')
# 检查文件是否存在
if path.exists():
print('File exists')
# 创建目录
path.parent.mkdir(parents=True, exist_ok=True)
# 写入文件
path.write_text('Hello, World!')
# 读取文件
content = path.read_text()
print(content)
通过这些步骤,你可以在Ubuntu上使用Python进行各种文件操作。根据具体需求选择合适的模块和方法。