对多个文本文件使用相同的代码,并使用python生成多个文本文件作为输出

时间:2018-02-16 21:16:09

标签: python

我有超过30个文本文件。我需要对每个文本文件进行一些处理,然后将它们再次保存在具有不同名称的文本文件中。

示例-1:precise_case_words.txt ----处理---- precise_case_sentences.txt

示例-2:random_case_words.txt ----处理---- random_case_sentences.txt

就像我需要为所有文本文件做的那样。

现有代码:

new_list = []

with open('precise_case_words.txt') as inputfile:

    for line in inputfile:
        new_list.append(line)


final = open('precise_case_sentences.txt', 'w+')


for item in new_list:

    final.write("%s\n" % item)

我一直手动复制+粘贴此代码,并且每次都手动更改名称。请建议我使用 python 避免手动作业的解决方案。

3 个答案:

答案 0 :(得分:1)

假设您在当前目录中拥有所有* _case_words.txt

import glob

in_file = glob.glob('*_case_words.txt')

prefix = [i.split('_')[0] for i in in_file]

for i, ifile in enumerate(in_file):
    data = []
    with open(ifile, 'r') as f:
        for line in f:
            data.append(line)
    with open(prefix[i] + '_case_sentence.txt' , 'w') as f:
        f.write(data)

答案 1 :(得分:0)

这可以让您了解如何处理它:

def rename(name,suffix):
    """renames a file with one . in it by splitting and inserting suffix before the ."""
    a,b = name.split('.')             
    return ''.join([a,suffix,'.',b])  # recombine parts including suffix in it

def processFn(name):
    """Open file 'name', process it, save it under other name"""    
    # scramble data by sorting and writing anew to renamed file            
    with open(name,"r") as r,   open(rename(name,"_mang"),"w") as w:
        for line in r:
            scrambled = ''.join(sorted(line.strip("\n")))+"\n"
            w.write(scrambled)

# list of filenames, see link below for how to get them with os.listdir() 
names = ['fn1.txt','fn2.txt','fn3.txt']  

# create demo data
for name in names:
    with open(name,"w") as w:
        for i in range(12):
            w.write("someword"+str(i)+"\n")

# process files
for name in names:
    processFn(name)

对于文件列表:请参阅How do I list all files of a directory?

我选择逐行读/写,你可以完全读入一个文件,处理它并根据你的喜好再次输出。

fn1.txt

someword0
someword1
someword2
someword3
someword4
someword5
someword6
someword7
someword8
someword9
someword10          
someword11          

进入fn1_mang.txt

0demoorsw
1demoorsw
2demoorsw
3demoorsw
4demoorsw
5demoorsw
6demoorsw
7demoorsw
8demoorsw
9demoorsw
01demoorsw
11demoorsw

答案 2 :(得分:0)

我今天恰好写了some code来做这件事。