【问题标题】:Reading the contents of a file whose name is stored in a variable读取名称存储在变量中的文件的内容
【发布时间】:2021-01-12 19:05:32
【问题描述】:

以下代码首先创建一个名为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()))

【问题讨论】:

    标签: python file variables directory


    【解决方案1】:

    直接改成

    read = open(f'films/{listoffiles[0]}',"r")
    

    【讨论】:

      【解决方案2】:
      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()))
      

      不确定您的逻辑,但您可以使用+ 运算符组成一个字符串。

      【讨论】:

        【解决方案3】:

        如果“文件名是变量”则表示字符串。

        因此您可以执行以下操作:

        with open(filenames) as open_file: 
            print(open_file.readlines())
        

        (或者在你的情况下扩展)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-21
          • 2016-03-16
          • 2017-06-18
          • 2021-11-17
          • 2018-01-10
          • 2015-10-28
          相关资源
          最近更新 更多