在Ubuntu中,Python可以通过内置的open()
函数进行文件操作。open()
函数用于打开一个文件,并返回一个文件对象,然后可以使用该文件对象进行读写操作。以下是一些基本的文件操作示例:
# 打开一个文件用于读取
file = open('example.txt', 'r')
# 打开一个文件用于写入(如果文件不存在,会自动创建)
file = open('example.txt', 'w')
# 打开一个文件用于追加(如果文件不存在,会自动创建)
file = open('example.txt', 'a')
# 读取整个文件内容
content = file.read()
print(content)
# 逐行读取文件内容
for line in file:
print(line, end='')
# 读取指定数量的字符
content = file.read(10)
print(content)
# 关闭文件
file.close()
# 写入字符串到文件
file.write('Hello, World!\n')
# 写入多行内容
file.writelines(['Line 1\n', 'Line 2\n'])
# 关闭文件
file.close()
# 追加字符串到文件
file.write('Appended text\n')
# 关闭文件
file.close()
with
语句进行文件操作使用with
语句可以自动管理文件的打开和关闭,即使在发生异常时也能确保文件被正确关闭。
# 读取文件
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# 写入文件
with open('example.txt', 'w') as file:
file.write('New content')
# 追加内容到文件
with open('example.txt', 'a') as file:
file.write('Appended text')
在Ubuntu中,文件路径通常使用正斜杠(/
)作为分隔符。可以使用Python的os
模块来处理文件路径。
import os
# 获取当前工作目录
current_directory = os.getcwd()
print(current_directory)
# 拼接文件路径
file_path = os.path.join(current_directory, 'example.txt')
print(file_path)
# 检查文件是否存在
if os.path.exists(file_path):
print('File exists')
else:
print('File does not exist')
# 创建目录
os.makedirs('new_directory', exist_ok=True)
# 删除文件
os.remove(file_path)
# 删除目录
os.rmdir('new_directory')
通过这些基本的文件操作,你可以在Ubuntu中使用Python进行各种文件处理任务。