【转】Python文件读写操作
Python对文件读写的操作还是比较简单的,功能也比较全,但是一些生僻的方法我们不常接触到,就不重复写了,转载一篇Dreamer博客上的文章,以备查看。这篇文章写得也还算详细了。
#打开文件和进行写操作
f=open(‘test.txt’,’w’)
f.write(‘hello’)
f.writelines([‘hi’,’haha’])#多行输入
f.close()
#append data
f=open(‘test.txt’,’a’)
f.write(‘hello’)
f.writelines([‘hi’,’haha’])
f.close()
#连续写入后会自动关闭
open(‘test.txt’,’a’).write(‘11111\r\n’)
#把result里的元素依次填到open函数里去
result={‘hello’,’u’}
exec open(‘test.txt’) in result
selected = [] # temp list to hold matches
fp = open(‘test.txt’)
for line in fp.readlines(): # Py2.2 -> “for line in fp:”
selected.append(line)
del line # Cleanup transient variable
open(‘test.txt’).readlines()
[……]