简体   繁体   中英

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!

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM