对多个文本文件使用相同的代码,并使用python生成多个文本文件作为输出
我有30多个文本文件。我需要对每个文本文件进行一些处理,然后用不同的名称将它们再次保存在文本文件中 示例1:precise_case_words.txt-processing-precise_case_句子.txt 示例2:random\u case\u words.txt-processing-random\u case\u句子.txt 像这样,我需要做的所有文本文件 现行代码:对多个文本文件使用相同的代码,并使用python生成多个文本文件作为输出,python,Python,我有30多个文本文件。我需要对每个文本文件进行一些处理,然后用不同的名称将它们再次保存在文本文件中 示例1:precise_case_words.txt-processing-precise_case_句子.txt 示例2:random\u case\u words.txt-processing-random\u case\u句子.txt 像这样,我需要做的所有文本文件 现行代码: 我一直在手动复制并粘贴此代码,每次都手动更改名称。请给我建议一个避免使用python手工作业的解决方案。假设您的*
我一直在手动复制并粘贴此代码,每次都手动更改名称。请给我建议一个避免使用python手工作业的解决方案。假设您的*\u case\u 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)
这应该让您了解如何处理它:
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)
有关文件列表:请参阅
我选择逐行读/写,您可以完全读取一个文件,处理它,然后根据您的喜好在块上再次输出它
fn1.txt:
进入fn1_mang.txt:
就在今天,我碰巧写了一篇这样的文章。将功能抽象为一个函数,并在循环中调用它
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)
someword0
someword1
someword2
someword3
someword4
someword5
someword6
someword7
someword8
someword9
someword10
someword11
0demoorsw
1demoorsw
2demoorsw
3demoorsw
4demoorsw
5demoorsw
6demoorsw
7demoorsw
8demoorsw
9demoorsw
01demoorsw
11demoorsw