如何使用Python进行文件读写操作

原创 - 日理万妓 2025-01-01 04:57 99阅读 0赞

在Python中,我们可以使用内置的open()函数来进行文件的读写操作。这个函数的基本语法如下:

  1. file_operation = open(file_path, mode)

其中:

  • file_path: 你需要打开的文件的路径。
  • mode: 文件模式,决定了你将做什么操作(如’r’代表读取,’w’代表写入覆盖等)。

下面是一些基本的操作示例:

  1. 读取文件

    1. with open('example.txt', 'r') as file:
    2. content = file.read()
    3. print(content)
  2. 写入文件(追加模式)

    1. with open('example.txt', 'a') as file:
    2. file.write('\nThis is a new line.\n')
  3. 写入文件(覆盖模式)

    1. with open('example.txt', 'w') as file:
    2. file.write('Hello, world!\n')

注意:在进行文件操作时,如果文件不存在,open()会创建一个新文件。如果文件已存在并且你希望覆盖其内容,则应使用模式’w’。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,99人围观)

还没有评论,来说两句吧...

相关阅读