Python Forum

Full Version: [split] Is there some coding that will do the following in 3 separate events?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2 3
This will read multiple input files and combine into one output file:

import os

# make sure in same directory as source file (you can modify path as desired)
os.chdir(os.path.abspath(os.path.dirname(__file__)))

input_files = ['firstfile.txt', 'secondfile.txt']


for file in input_files:
    with open(file) as fin, open('thirdfile.txt', "a+") as fout:
        fout.write(fin.read())
test:
firstfile.txt:
Output:
Data from first file
secondfile.txt
Output:
Data from second file.
thirdfile.txt:
Output:
Data from first file Data from second file.
In line 5 change the w to an a - as in append. That will then write to the end of the second file.
(Jul-25-2021, 11:25 AM)jefsummers Wrote: [ -> ]In line 5 change the w to an a - as in append. That will then write to the end of the second file.

Thanks @jefsummers - The filename (advert) will remain constant so will be no problem there. However, the output_filename will vary because it will be selected by the user (category).

Is there any way the outfile will "write" upon the "user" opening of that file?
Sure. The input filename and output filename can be variables
Pages: 1 2 3