Python 写入文件

 

 

打开文件时,可指定

读取模式('r')

写入模式('w')

附加模式('a')

读写模式('r+')

如果省略了模式实参,Python将以默认的只读模式打开文件。

如果要写入的文件不存在,函数open()将自动创建它。然而,以写入模式('w')打开文件时千万要小心,因为如果指定的文件已经存在,Python将在返回文件对象前清空该文件的内容

注意 Python只能将字符串写入文本文件。要将数值数据存储到文本文件中,必须先使用函数str()将其转换为字符串格式。

filename = 'test.txt'

#读取:
with open(filename, 'w', encoding='utf-8') as fileobj:
    fileobj.write('Hello Python\n 潘森')

#写入:
with open(filename, 'r', encoding='utf-8') as fileobj:
    for line in fileobj:
        print(line.rstrip())

 

附加模式打开文件进行追加写入

name = input('Input Your Name : ')

file = 'guest.txt'
with open(file, 'a', encoding='utf-8') as fileobj:
    fileobj.write(name+'\n')

with open(file, 'r', encoding='utf-8') as fileobj:
    for line in fileobj:
        print(line.rstrip())

 

posted @ 2021-09-22 15:44  茶叶蛋蛋  阅读(2929)  评论(0)    收藏  举报