How to speed up process in Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to speed up process in Python

Hello. I have this code here that basically puts text documents into 1 text document. filenames = [‘10k mails_1’, ‘10k mails_2’, ...] with open(‘C:\Users\Caesar Ronin \Desktop\All Mails.txt’, ‘w’) as outfile: for fname in filenames: with open(fname) as infile: for line in infile: outfile.write(line) It works perfectly, however, I want to put in multiple .txt documents at where the ... is at, without having to write them 1 by 1. Could there be a code that for example lets me add +1 to the end of the .txt at filenames since they’re numbered with the same filename? So maybe a loop that adds +1 so it becomes 10k mails_3, 10k mails_4 etc. up until for example < 100 without me having to write the full name, or even the numbers.

6th Feb 2021, 2:19 PM
Sidar Sahin
3 Answers
+ 3
You can combine Python3 F-String and list comprehension to generate list of file names (based on Abhay's example) max_number = 100 # change as necessary filenames = [ f"10k_mail_{n}.txt" for n in range( 1, max_number + 1 ) ] print( file_names )
6th Feb 2021, 2:30 PM
Ipang
+ 6
Sidar Sahin filenames = ["10k mails_1","10k mails_2",*('10k mails_'+str(i) for i in range(3,100))]
6th Feb 2021, 2:24 PM
Abhay
Abhay - avatar
0
I get at the line of for fname in filenames: FileNotFoundError: [Errno 2] No such file or directory: ‘10k mails_2’ So it is referring to the filenames that have been created using *list ...
6th Feb 2021, 2:49 PM
Sidar Sahin