我的代码遍历文件夹中的txt文件,然后提取标题(包含“ | SYS”的行,并将它们写入另一个文件)。 但是,当找不到文件时,代码将完全失败而不会出现错误。 例如。它搜索文件名中包含USR02,USR06、1251和TEXTS的文件。 但是当某些文件包含例如找不到1251,它不搜索包含“ TEXTS”的下一个文件。没有错误信息。 有什么想法吗?
from glob import glob
import fileinput
table02 = ('FINAL' + '\\'+ '0a_USR02.txt')
with open(table02, 'w') as out:
for line in fileinput.input(glob('*USR02.txt')):
if '| SYS' in line:
out.write(line)
table06 = ('FINAL' + '\\'+ '0a_USR06.txt')
with open(table06, 'w') as out:
for line in fileinput.input(glob('*USR06.txt')):
if '| SYS' in line:
out.write(line)
table09 = ('FINAL' + '\\'+ '0a_AGR_TEXTS.txt')
with open(table09, 'w') as out:
for line in fileinput.input(glob('*TEXTS.txt')):
if '| SYS' in line:
out.write(line)
table03 = ('FINAL' + '\\'+ '0a_AGR_1251.txt')
with open(table03, 'w') as out:
for line in fileinput.input(glob('1251.txt')):
if '| SYS' in line:
out.write(line)
答案 0 :(得分:0)
彻底检修,文件组将包含特定表达式的所有行写入按名称分组的一个文件。
from glob import glob
import fileinput
import os
cwd = os.getcwd()
directory = cwd
flatfiles = ['UST04', 'USR02', 'USR06','1251', 'AGRS', 'TEXTS',\
'USERS', 'FLAGS', 'DEVACCESS', 'USERNAME', 'TSTC', 'TSTCT']
for flatfile in flatfiles:
for file in os.listdir(directory):
if file.endswith(flatfile + ".txt"):
table03 = ('FINAL' + '\\'+ '0a_' + flatfile + '.txt')
with open(table03, 'w+') as out:
for line in fileinput.input(glob('*'+ flatfile +'.txt')):
if '| SYS' in line:
out.write(line)
else:
pass