【问题标题】:Need help for making this .txt files TRUE需要帮助以使此 .txt 文件为 TRUE
【发布时间】:2021-10-27 03:25:42
【问题描述】:

大家好,我怎样才能让这件事变成 TRUE?我已经存在 .txt 文件,但结果总是 False。

ID = input("Enter the name of your .txt file: ") +".txt" +"'"
IDS = "'" + ID
file_exists = os.path.exists(IDS)
print(file_exists)
print(IDS)

【问题讨论】:

    标签: python text operating-system


    【解决方案1】:

    去掉文件名前后的'

    ID = input("Enter the name of your .txt file: ") +".txt"
    file_exists = os.path.exists(ID)
    print(file_exists)
    print(ID)
    

    例如,如果您有foo.txt 并且您将foo 放入您的程序中,那么您当前的代码将查找名为'foo.txt' 的文件,不是foo.txt。 p>

    【讨论】:

    • 老兄,非常感谢!我确实依赖'Sample.txt'..再次感谢你,我现在终于明白了
    【解决方案2】:

    试试这个:

    #You may want to use str.strip() to get rid of unnecessary whitespaces
    ID = input("Enter the name of your .txt file: ").strip() + ".txt"
    file_exists = os.path.exists(ID)
    print(f'{ID} exists') if file_exists else print(f'{ID} file does not exist')
    

    【讨论】:

      【解决方案3】:

      删除引号,您将在字符串的开头和结尾添加单引号。您的代码应如下所示:

      ID = input("Enter the name of your .txt file: ") +".txt" 
      file_exists = os.path.exists(ID)
      print(file_exists)
      print(IDS)
      

      编程语言中的引号表示什么是字符串,当您将其输出到终端(打印)时,解释器会省略它们

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-14
        • 2013-10-09
        • 2010-11-04
        相关资源
        最近更新 更多