我的程序无法正确读取文件

时间:2020-12-28 12:09:36

标签: python

我认为以下代码的效率不足以搜索当前目录中的文件名。文件名将存储为字符串,那么 python 是否能够从非字符串的目录中搜索“文件名”字符串?

filename = input("What would you like to name the File? ")
import os
if f"{filename}.txt" in os.getcwd():
    print(True)

3 个答案:

答案 0 :(得分:0)

os.getcwd() 返回目录本身的名称,而不是文件列表(参见 https://www.tutorialspoint.com/python/os_getcwd.htm

您想尝试以下操作:

import os
for file in os.listdir("/mydir"):
    if file == f"{filename}.txt:
        print("File Found")

答案 1 :(得分:0)

此外,对于此代码段,您需要 try-except statement。否则,在错误的文件中,应用程序将崩溃。

答案 2 :(得分:0)

import os 
# Getting current folder path
cmd = os.getcwd()
    # getting file name from user
    file_name = input('Enter file name to be search : ')
    #Looping through all folder and files in the current directory
    for file in os.listdir(cmd):
        # compare the file name user entered with file names from current 
        # directory file name
        if file == f"{file_name}.txt":
            print("File Found")
相关问题