在Ubuntu中,Python处理文件操作主要通过内置的open()函数和文件对象的方法来实现。以下是一些基本的文件操作示例:
# 打开一个文件,如果不存在则会创建一个新文件
file = open("example.txt", "w") # "w"模式表示写入模式,如果文件已存在,将会被覆盖
file.write("Hello, World!")
file.close()
# 以只读模式打开文件
file = open("example.txt", "r")
# 读取文件内容
content = file.read()
print(content)
# 关闭文件
file.close()
file = open("example.txt", "r")
for line in file:
print(line.strip()) # strip()方法用于去除字符串两端的空白字符
file.close()
file = open("example.txt", "a") # "a"模式表示追加模式
file.write("\nThis is a new line.")
file.close()
with语句自动关闭文件:# 使用with语句打开文件,无需手动调用close()方法
with open("example.txt", "w") as file:
file.write("Hello, World!")
# 文件会在with语句块结束时自动关闭
注意:在实际编程中,建议使用with语句来处理文件操作,因为它可以确保文件在操作完成后被正确关闭,避免资源泄露。