【问题标题】:How do I open a file with Python with the file name contained in a String?如何使用 Python 打开文件名包含在字符串中的文件?
【发布时间】:2021-08-17 15:48:30
【问题描述】:

如果文件名的单词包含在字符串中,有没有办法打开文件?在这里,我将单词键存储在变量'query'中,我希望如果单词'keys'是字符串'query'的值,它应该打开文件'keys indrawer.txt',因为它包含单词键,或者如果'query'的值是'pen',它应该打开文件'pen on table'.txt。 这是table.txt文件上的笔:

pen is on the table

drawer.txt 中的键

the keys are in the drawer

我该怎么做?我知道这有点复杂,但请尝试回答这个问题,我从过去 2 天开始就在这个问题上!

query=("keys")
list_directory=listdir("E:\\Python_Projects\\Sandwich\\user_data\\Remember things\\")
     
 if query in list_directory: 
                with open(f"E:\\Python_Projects\\Sandwich\\user_data\\Remember things\\ 
                {list_directory}",'r') as file:
                    read_file=file.read
                    print(read_file)
                    file.close
                    pass

此代码由于某种原因不起作用。

【问题讨论】:

  • 为什么passfil.close() 方法之后
  • 通过查看代码with open(f"E:\\Python_Projects\\Sandwich\\user_data\\Remember things\\{list_directory}.txt",'r'),您可能忘记了.txt 扩展

标签: python file directory txt listdir


【解决方案1】:

read() 和 close() 是方法,而不是属性。你应该写file.read() 而不是file.read。另外,使用 with 关键字时关闭文件是多余的。

【讨论】:

    【解决方案2】:

    list_directory 是字符串列表,而不是字符串。这意味着您需要对其进行迭代以便将列表中的每个字符串与您的查询进行比较

    您还需要调用file.readfile.close 方法,在它们后面加上括号(file.read()file.close()),否则它们不会执行。

    这个重新编写的代码应该可以解决问题:

    query = "keys"
    path = "E:\\Python_Projects\\Sandwich\\user_data\\Remember things\\"
    
    list_directory = listdir(path)
    for file_name in list_directory:
        if query in file_name:
            with open(f"{path}{file_name}",'r') as file:
                content = file.read()
                print(content)
                file.close()
    

    【讨论】:

    • with open(os.path.join(path,file_name),'r')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 2016-07-17
    • 1970-01-01
    • 2020-08-28
    • 2011-06-08
    • 1970-01-01
    • 2017-09-24
    相关资源
    最近更新 更多