Python的文件读取操作主要通过内置的open()
函数来实现。
示例:
# 打开文件
file = open("text.txt", "r")
# 读取文件内容
content = file.read()
# 关闭文件
file.close()
# 输出文件内容
print(content)
Python的文件写操作:
# 打开文件,如果文件不存在则创建
file = open("text.txt", "w")
# 写入内容
file.write("Hello, World!")
# 关闭文件
file.close()
Python中对文件进行增加操作
# 打开文件,如果文件不存在则创建
file = open("text.txt", "a")
# 写入内容
file.write("这是一行新的内容。
")
# 关闭文件
file.close()