如何使用Python进行文件读写操作
在Python中,我们可以使用内置的open()
函数来进行文件的读写操作。这个函数的基本语法如下:
file_operation = open(file_path, mode)
其中:
file_path
: 你需要打开的文件的路径。mode
: 文件模式,决定了你将做什么操作(如’r’代表读取,’w’代表写入覆盖等)。
下面是一些基本的操作示例:
读取文件:
with open('example.txt', 'r') as file:
content = file.read()
print(content)
写入文件(追加模式):
with open('example.txt', 'a') as file:
file.write('\nThis is a new line.\n')
写入文件(覆盖模式):
with open('example.txt', 'w') as file:
file.write('Hello, world!\n')
注意:在进行文件操作时,如果文件不存在,open()
会创建一个新文件。如果文件已存在并且你希望覆盖其内容,则应使用模式’w’。
还没有评论,来说两句吧...