learnFile.py
绝对路径
# coding=UTF-8 import sys reload(sys) with open(r‘C:\Users\zhujiachun\Desktop\test_text.txt‘,‘r‘) as file_object: contents = file_object.read() print contents
在learnFile.py所在的目录中查找test_text.txt 并打开
# coding=UTF-8 import sys reload(sys) with open(‘test_text.txt‘) as file_object: contents = file_object.read() print contents
with open():在不需要访问文件后将其关闭
也可以用open(),close()。但如果程序存在bug,可能导致close()不执行,文件不关闭。
因此推荐用with open()方法
结果:
如果你要是对文件进行写入操作应该这样
f=open(r‘c:\fenxi.txt’,‘w‘)
如果是只是读取:
f=open(r‘c:\fenxi.txt’,‘r‘)
read()到达文件末尾会返回一个空字符串,显示出来就是一个空行
可使用rstrip():
删除空格用strip()
# coding=UTF-8 import sys reload(sys) with open(‘test_text.txt‘) as file_object: contents = file_object.read() print contents.rstrip()
使用for循环读取每一行
# coding=UTF-8 with open(‘test_text.txt‘) as file_object: for line in file_object: print line.rstrip()
储存在列表中读取
# coding=UTF-8 with open(‘test_text.txt‘) as file_object: lines = file_object.readlines() for line in lines: print line.rstrip()
原文:https://www.cnblogs.com/erchun/p/11766173.html