Python读取、写入文件

version:2.7

1 读取



读取时,在win下,不能用直接复制过来的路径,要把\改成/,同时路径不能含有中文(默认编码下)

In [170]: path = 'F:/t1.txt'

In [171]: lines = [x.rstrip() for x in open(path)]

In [172]: lines
Out[172]: ['123', '456', '789']

In [173]: path = 'F:\t1.txt'

In [174]: lines = [x.rstrip() for x in open(path)]

IOErrorTraceback (most recent call last)
<ipython-input-174-1e02eb79039e> in <module>()
----> 1 lines = [x.rstrip() for x in open(path)]

IOError: [Errno 22] invalid mode ('r') or filename: 'F:\t1.txt' 

In [175]: path = 'F:/经典书籍/t1.txt'

In [176]: lines = [x.rstrip() for x in open(path)]

IOErrorTraceback (most recent call last)
<ipython-input-176-1e02eb79039e> in <module>()
----> 1 lines = [x.rstrip() for x in open(path)]

IOError: [Errno 2] No such file or directory: 'F:/\xe7\xbb\x8f\xe5\x85\xb8\xe4\xb9\xa6\xe7\xb1\x8d/t1.txt' 
In [187]: f=open("F:/t1.txt","r")

In [188]: f.read()
Out[188]: '123\n456\n789'

In [189]: print f.read() ##无输出

In [195]: f=open("F:/t1.txt","r")

In [196]: print f.readlines() ##注意这里是小写的L
['123\n', '456\n', '789']
In [197]: f=open("F:/t1.txt","r")

In [198]: for line in f:
     ...:     if '3' in line:
     ...:         print 'this is ths first line'
     ...:     else:
     ...:         print line
     ...:         
this is ths first line
456

789

2 写入

In [202]: f=open('F:/t1.txt','w') ##原来的文件被删除,会立即以该文件名创建新的文件。此时文件的创建时间为17:23

In [204]: f.write('hunan') ##无换行

In [205]: f.write('hubei\n') ##有换行

In [206]: f.write('hebei\n') ##文件仍然为空

In [209]: f.close() ##此时才会写入文件,之前一直为空。此时文件的修改时间会变为17:25


3 追加

f=open('F:/t1.txt','a')

f.write('anhui')

f.write('jiangsu\n')

f.write('zhejiang\n')

f.close() #文件的修改时间变为17:33

参考:

https://www.cnblogs.com/kele-1314/p/6182548.html

扫描二维码关注公众号,回复: 1073522 查看本文章

https://my.oschina.net/u/2252538/blog/332757

猜你喜欢

转载自blog.csdn.net/u010002184/article/details/80031389