读取名称存储在变量中的文件的内容
Reading the contents of a file whose name is stored in a variable
以下代码首先创建名为 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()))
path = 'films'
from os import walk
f = []
for (filenames) in walk(path):
f.extend(filenames)
break
listoffiles = f[2]
print("listoffiles: ",listoffiles)
read = open('sentences/'+listoffiles[0],"r")
print("read: ",str(read.read()))
不确定您的逻辑,但您可以使用 +
运算符组成一个字符串。
改成
read = open(f'films/{listoffiles[0]}',"r")
如果“文件名是一个变量”代表字符串。
因此您可以执行以下操作:
with open(filenames) as open_file:
print(open_file.readlines())
(或者在你的情况下扩展)
以下代码首先创建名为 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()))
path = 'films'
from os import walk
f = []
for (filenames) in walk(path):
f.extend(filenames)
break
listoffiles = f[2]
print("listoffiles: ",listoffiles)
read = open('sentences/'+listoffiles[0],"r")
print("read: ",str(read.read()))
不确定您的逻辑,但您可以使用 +
运算符组成一个字符串。
改成
read = open(f'films/{listoffiles[0]}',"r")
如果“文件名是一个变量”代表字符串。
因此您可以执行以下操作:
with open(filenames) as open_file:
print(open_file.readlines())
(或者在你的情况下扩展)