![](/img/trans.png)
[英]How to load and apply same algorithm on multiple text files using python
[英]Using same code for multiple text files and generate multiple text files as output using python
我有30多個文本文件。 我需要對每個文本文件進行一些處理,然后再次將它們保存在具有不同名稱的文本文件中。
示例1:precision_case_words.txt ----處理中---- precision_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手動作業的解決方案。
假設您在當前目錄中擁有所有* _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)
這應該使您了解如何處理它:
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
:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.