Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 读取名称存储在变量中的文件的内容_Python_File_Variables_Directory - Fatal编程技术网

Python 读取名称存储在变量中的文件的内容

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: "

下面的代码首先创建名为films的文件夹中所有文件的列表,然后尝试访问特定文件的内容。我知道如果文件名是一个文本,怎么做,但是如果文件名或目录名是一个变量,有人能解释一下怎么做吗

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())
(或在您的情况下扩展)