读取多个文件并写入多个输出文件
如果我在一个名为C的文件夹里有多个文件,我想写一段代码,自动读取所有的文件,处理每个文件,然后为每个输入文件写一个输出文件。
比如在C文件夹里,我有以下这些文件:
aba
cbr
wos
grebedit
scor
提示:这些文件没有明显的扩展名
然后程序会一个一个地读取这些文件,进行处理,然后把输出写到这个文件夹里:
aba.out
cbr.out
wos.out
grebedit.out
scor.out
1 个回答
2
让我给你推荐一个教程。当你对文件的输入和输出有了一定了解后,这里有一个基本的工作流程可以让你进一步学习。
def do_something(lines):
output = []
for line in lines:
# Do whatever you need to do.
newline = line.upper()
output.append(newline)
return '\n'.join(output) #
listfiles = ['aba', 'cbr', 'wos', 'grebedit', 'scor']
for f in listfiles:
try:
infile = open(f, 'r')
outfile = open(f+'.out', 'w')
processed = do_something(infile.readlines())
outfile.write(processed)
infile.close()
outfile.close()
except:
# Do some error handling here
print 'Error!'
如果你需要从某个文件夹里的所有文件中创建一个列表,可以使用os
模块。
import os
listfiles = os.listdir(r'C:\test')