Chase Garfield
Chase Garfield

Reputation: 127

Writing multiple files into one file using Python, while taking input from the user to choose the files to scan

Ok, so I have code that looks like this:

input_name="PLACEHOLDER"

while input_name != "":
    input_name=input('Part Name: ')


with open("/pathway/%s.txt" %input_name ,"r") as read_data, open("output.txt","w") as output:

if part_name != "":
    f=input_data.read() 
    print(input_data)

    output.write(part_name)
    output.write(date)
    output.write(y)
else:
    read_data.close()   
    output.close()

I know it looks a little broken, but what I need to do is fix the loop, because I need to be able to take multiple inputs, and write each of those inputs(file names) to the same file at the end of the program. I probably need at least one more loop in here, I'm just looking for ideas or a kick in the right direction. I have other formatting code in there, this is just the bare bones, looking for an idea on what kind of loops I could run. Thanks to anyone who takes the time to look at this for me!

Upvotes: 1

Views: 847

Answers (2)

Xander Luciano
Xander Luciano

Reputation: 3883

Just going to mockup some code for you to help guide you, no guarantees this will work to any degree, but should get you started.

First off, lets store all the part names in a list so we can loop over them later on:

input_name = []
user_input = input('Part Name: ')
while user_input != "":
    input_name.append(user_input)
    user_input = input('Part Name: ')

Now let's loop through all the files that we just got:

for (file_name in input_name):
    with open("/pathway/%s.txt" %file_name ,"r") as read_data, open("output.txt","w") as output:
        # any thing file related here
        print(input_data)
        output.write(part_name)
        output.write(date)
        output.write(y)
print("All done")

That way you get all the user input at once, and process all the data at once.

Upvotes: 1

Marco
Marco

Reputation: 887

You can keep the output.txt open from the beginning of the execution and open each file after the user input its name.

Example (not tested):

with open("output.txt","w") as output:

    while True:
        input_name = input('Part Name: ').strip()

        if input_name == '':
            break

        with open("/pathway/%s.txt" %input_name ,"r") as read_data:

            if part_name != "":
                output.write(read_data.read())

Remember that you don't need to close the file if you open it in with

Upvotes: 1

Related Questions