在 Ubuntu 系统中,Python 文件操作主要涉及到以下几个方面:
以下是一些常用的 Python 文件操作方法:
# 使用 open() 函数打开文件,参数为文件名和模式('r' 读取,'w' 写入,'a' 追加)
file = open("example.txt", "r")
# 读取文件的全部内容
content = file.read()
# 逐行读取文件内容
for line in file:
print(line)
# 读取指定字节数的内容
content = file.read(10)
# 向文件中写入字符串
file.write("Hello, World!")
# 向文件中写入多行字符串
file.writelines(["Line 1\n", "Line 2\n"])
# 使用 close() 方法关闭文件
file.close()
# 使用 with 语句打开文件,这样可以确保文件在操作完成后自动关闭
with open("example.txt", "r") as file:
content = file.read()
print(content)
这是一个简单的 Python 文件操作示例:
# 创建一个新文件并写入内容
with open("example.txt", "w") as file:
file.write("Hello, World!")
# 读取文件内容并打印
with open("example.txt", "r") as file:
content = file.read()
print(content)
在 Ubuntu 系统中,你可以使用任何文本编辑器(如 Vim、Nano 或 Gedit)创建和编辑 Python 文件。保存文件后,在终端中使用 python3 文件名.py 命令运行 Python 脚本。