读取多个文件并写入多个输出文件

2024-09-27 02:23:15 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我在一个目录C中有多个文件,我想写一个代码(自动地)读取所有文件并处理每个文件,然后为每个输入文件编写一个输出文件。在

例如,在目录C中,我有以下文件:

aba 
cbr
wos
grebedit
scor

提示:这些文件没有明显的扩展名

然后程序逐个读取这些文件,进行处理,然后将输出写入目录:

^{pr2}$

Tags: 文件代码程序目录cbrwosabapr2
1条回答
网友
1楼 · 发布于 2024-09-27 02:23:15

请允许我告诉你去tutorial。一旦您对一般的文件IO感到满意,这里有一个基本的工作流供您扩展。在

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模块。在

^{pr2}$

相关问题 更多 >

    热门问题