Python文件读取 并按格式输出文件内容
2018-03-15 本文已影响672人
莫尛莫
需要读取的文件内容:http://python.itcarlow.ie/chapter3/sketch.txt
1. 切换工作目录
代码:
import os
os.chdir('D:/') # 注意斜杠方向
print(os.getcwd())
输出:
D:\
2. 打开文件open()
代码:
try:
data = open('sketch.txt')
print(data.readline(), end='') # 读取一行内容
print(data.readline(), end='') # 读取二行内容
data.seek(0) # 返回文件起始位置
except IOError:
print('The data file is missing!')
输出:
Man: Is this the right room for an argument?
Other Man: I've told you once.
0
3. 输出所有内容
代码:
for each_line in data:
try:
(role, line_spoken) = each_line.split(':', 1)
print(role, end='')
print(' said: ', end='')
print(line_spoken, end='')
except ValueError: # 因为数据中存在多个冒号和没有冒号的数据,需要处理产生的错误,
print(each_line)
部分输出:
Man said: Is this the right room for an argument?
Other Man said: I've told you once.
... ...
Man said: (exasperated) Oh, this is futile!!
Other Man said: No it isn't!
Man said: Yes it is!
4. 关闭文件
代码:
if 'data' in locals():
data.close()
# 或者使用with打开文件,则不需要手动close:
with open('sketch.txt', 'w') as data:
5. 完整代码
try:
with open('sketch.txt') as data:
for each_line in data:
try:
(role, line_spoken) = each_line.split(':', 1) # split('', 1)处理多个冒号的情况,只分一次;
print(role, end='')
print(' said: ', end='')
print(line_spoken, end='')
except ValueError: # 因为数据中存在没有冒号的数据,需要处理产生的错误;
print(each_line)
except IOError as err:
print('IOError: ' + str(err))