[英]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. 您可以从执行开始就保持
output.txt
打开,并在用户输入文件名后打开每个文件。
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
请记住,你并不需要,如果你在打开关闭文件
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. 这样,您可以一次获得所有用户输入,并立即处理所有数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.