0

I have more than 30 text files. I need to do some processing on each text file and save them again in text files with different names.

Example-1: precise_case_words.txt ---- processing ---- precise_case_sentences.txt

Example-2: random_case_words.txt ---- processing ---- random_case_sentences.txt

Like this i need to do for all text files.

present code:

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)

Am manually copy+paste this code all the times and manually changing the names everytime. Please suggest me a solution to avoid manual job using python.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
kumar
  • 629
  • 1
  • 6
  • 9

3 Answers3

1

Suppose you have all your *_case_words.txt in the present dir

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)
Osman Mamun
  • 2,864
  • 1
  • 16
  • 22
0

This should give you an idea about how to handle it:

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)

For file listings: see How do I list all files of a directory?

I choose to read/write line by line, you can read in one file fully, process it and output it again on block to your liking.

fn1.txt:

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

into fn1_mang.txt:

0demoorsw
1demoorsw
2demoorsw
3demoorsw
4demoorsw
5demoorsw
6demoorsw
7demoorsw
8demoorsw
9demoorsw
01demoorsw
11demoorsw
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

I happened just today to be writing some code that does this.

Jeffrey Benjamin Brown
  • 3,427
  • 2
  • 28
  • 40