9–1. 文件过滤. 显示一个文件的所有行, 忽略以井号( # )开头的行. 这个字符被用做Python , Perl, Tcl, 等大多脚本文件的注释符号.
9–2. 文件访问. 提示输入数字 N 和文件 F, 然后显示文件 F 的前 N 行.
9–7. 解析文件. Win32 用户: 创建一个用来解析 Windows .ini 文件的程序.
9–16. 文本处理. 人们输入的文字常常超过屏幕的最大宽度. 编写一个程序, 在一个文本
文件中查找长度大于 80 个字符的文本行. 从最接近 80 个字符的单词断行, 把剩余文件插入到
下一行处.
附加题: 处理不是第一个字符开头的注释.
def readFile():
fi = open('D:/test.txt', 'r')
listFile = []
for eachLine in fi:
if '#' not in eachLine:
listFile.append(eachLine)
else:
id = eachLine.index('#')
listFile.append(eachLine[:id])
for i in listFile:
print(i, end ='')
fi.close()
readFile()
9–2. 文件访问. 提示输入数字 N 和文件 F, 然后显示文件 F 的前 N 行.
def visitFile():
fileName = input('Please input the file name you wanna visit:')
nLine = int(input('Please input the line you wanna visit:'))
fi = open(fileName)
for eachLine in fi:
if nLine:
print(eachLine, end = '')
nLine -= 1
else:
break
fi.close()
def countLine():
fileName = input('Please input the file name:')
fi = open(fileName)
n = 0
for eachLine in fi:
n += 1
print(n)
fi.close()
9–4. 文件访问. 写一个逐页显示文本文件的程序. 提示输入一个文件名, 每次显示文本文件的 25 行, 暂停并向用户提示"按任意键继续.", 按键后继续执行.
def showLine():
fileName = input('Please input the file name:')
with open(fileName,'r') as fi:
i=1
for eachLine in fi:
print(eachLine, end = '')
if not i%25:
os.system('pause')
i+=1
9–6. 文件比较. 写一个比较两个文本文件的程序. 如果不同, 给出第一个不同处的行号和列号.
def cmp_file():
f1 = open('test1.txt', 'r')
f2 = open('test2.txt', 'r')
fo = zip(f1,f2)
Ln = 1
for (line1, line2) in fo:
if line1 == line2:
pass
else:
print('Ln:%s' %Ln, end = ' ')
Col = 1
for (a,b) in zip(line1,line2):
if a == b:
Col += 1
else:
print('Col:%s' %Col)
break
Ln += 1
f1.close()
f2.close()
9–7. 解析文件. Win32 用户: 创建一个用来解析 Windows .ini 文件的程序.
def parse_file():
parse = {}
with open(r'C:\Windows\win.ini') as file:
for line in file:
if line.startswith(';'):
continue
if line.startswith('['):
item = []
name = line[1:line.rfind(']')]
parse.setdefault(name,item)
continue
if '=' in line:
item.append(line.strip())
print(parse)
9–15. 复制文件. 提示输入两个文件名(或者使用命令行参数). 把第一个文件的内容复制到第二个文件中去.
def copy_file():
orgLine = ''
with open(r'test1.txt') as orgFile:
for eachLine in orgFile:
orgLine = orgLine+eachLine
with open('test2.txt', 'a') as destFile:
destFile.write(orgLine)
copy_file()
9–16. 文本处理. 人们输入的文字常常超过屏幕的最大宽度. 编写一个程序, 在一个文本
文件中查找长度大于 80 个字符的文本行. 从最接近 80 个字符的单词断行, 把剩余文件插入到
下一行处.
程序执行完毕后, 应该没有超过 80 个字符的文本行了.
def len80():
with open(r'test1.txt',) as fi:
with open('tmp.txt', 'w') as ft:
for eachLine in fi:
le = len(eachLine)
if le > 80:
lineList = list(eachLine)
count = int(len(lineList) / 80)
print(count)
for i in range(count):
ft.write(''.join(lineList[:80]))
ft.write('\n')
lineList = lineList[80:]
ft.write(''.join(lineList))
else:
ft.write(eachLine)
with open(r'tmp.txt') as ft:
with open('test1.txt', 'r+') as fi:
for i in ft:
fi.write(i)
os.remove('tmp.txt')