Python 之 文件操作

文件的增删改查操作

文件名:file1
1   2   3
one two three
一   二   三

1、查看文件内容

f = open('file1','r',encoding='utf-8')   #打开文件句柄
for line in f:                           #循环文件句柄内容
    print(line.strip())                  #打印每一行
f.close()                                #关闭文件

#结果:
1   2   3
one two three
一   二   三

2、往一个文件里追加内容

f = open('file1','a',encoding='utf-8')
f.write('追加一个新的内容!!!\n')
f.close()

#结果:
1   2   3
one two three
一   二   三
追加一个新的内容!!!

3、创建一个新的文件,并写入内容

f = open('file2','w',encoding='utf-8')
f.write('4  5   6\n')
f.write('四  五   六\n')
f.close()

#结果:file2
4  5   6
四  五   六

猜你喜欢

转载自blog.51cto.com/12965094/2345111
今日推荐