Python 读取名称存储在变量中的文件的内容
下面的代码首先创建名为films的文件夹中所有文件的列表,然后尝试访问特定文件的内容。我知道如果文件名是一个文本,怎么做,但是如果文件名或目录名是一个变量,有人能解释一下怎么做吗Python 读取名称存储在变量中的文件的内容,python,file,variables,directory,Python,File,Variables,Directory,下面的代码首先创建名为films的文件夹中所有文件的列表,然后尝试访问特定文件的内容。我知道如果文件名是一个文本,怎么做,但是如果文件名或目录名是一个变量,有人能解释一下怎么做吗 path = 'films' from os import walk f = [] for (filenames) in walk(path): f.extend(filenames) break listoffiles = f[2] print("listoffiles: "
path = 'films'
from os import walk
f = []
for (filenames) in walk(path):
f.extend(filenames)
break
listoffiles = f[2]
print("listoffiles: ",listoffiles)
read = open('films/{listoffiles[0]}',"r")
print("read: ",str(read.read()))
不确定您的逻辑,但您可以使用+
运算符组合字符串
不确定您的逻辑,但您可以使用+
运算符组合字符串。只需将其更改为
read = open(f'films/{listoffiles[0]}',"r")
把它改成
read = open(f'films/{listoffiles[0]}',"r")
如果“文件名是变量”,则表示字符串
因此,您可以执行以下操作:
with open(filenames) as open_file:
print(open_file.readlines())
(或者在您的例子中是extend)如果“文件名是变量”,则表示字符串
因此,您可以执行以下操作:
with open(filenames) as open_file:
print(open_file.readlines())
(或在您的情况下扩展)