简体   繁体   English

如何从列表中添加文本以打开文件?

[英]How can I add a text from a list to open a file?

I'd like to open a file but I don't want to write the name of the file everytime, that's why I want to create a list and then choose the element by putting 0,1,2... I don't understand how it works, I tried to do this but it doesn't work.我想打开一个文件,但我不想每次都写文件名,这就是为什么我想创建一个列表,然后通过放置 0,1,2 来选择元素......我不了解它是如何工作的,我试图这样做,但它不起作用。 Can anyone help me?谁能帮我?

L=["file1","file2","file3"]

file = open('D:/folder/'L[0]'.txt', 'r')

I think what your looking for here is string formatting or f-strings.我认为您在这里寻找的是字符串格式或 f 字符串。

Assuming you'd like to read information from a file with the path D:/folder/file1.txt' you should use f strings to format the correct path as such:假设您想从路径为D:/folder/file1.txt'的文件中读取信息,您应该使用 f 字符串来格式化正确的路径,如下所示:

file = open(f'D:/folder/{L[0]}.txt', 'r')

You can use this idea to iterate through your list and read the individual files and do what you need to do with it:您可以使用这个想法来遍历您的列表并读取各个文件并执行您需要执行的操作:

for filename in L:
    file = open(f'D:/folder/{filename}.txt', 'r')
    # Do operations for each file here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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