Python 我的程序可以';我不能正确地读取文件
我认为以下代码的效率不足以在当前目录中搜索文件名。文件名将存储为字符串,因此python能否从非字符串目录中搜索“filename”字符串Python 我的程序可以';我不能正确地读取文件,python,Python,我认为以下代码的效率不足以在当前目录中搜索文件名。文件名将存储为字符串,因此python能否从非字符串目录中搜索“filename”字符串 filename = input("What would you like to name the File? ") import os if f"{filename}.txt" in os.getcwd(): print(True) getcwd()返回目录本身的名称,而不是文件列表(请参阅) 您想尝试以下
filename = input("What would you like to name the File? ")
import os
if f"{filename}.txt" in os.getcwd():
print(True)
getcwd()返回目录本身的名称,而不是文件列表(请参阅)
您想尝试以下方法:
import os
for file in os.listdir("/mydir"):
if file == f"{filename}.txt:
print("File Found")
另外,您需要
为此代码段尝试EXPECT语句。否则,在错误的文件中,应用程序将崩溃。os.getcwd()
将只返回当前工作目录路径。您要做的是获取当前及其子目录中的所有文件名,然后将文件名与列表匹配。关于如何读取文件名,请检查此答案:请注意,此答案将作为注释而不是答案添加。此答案不提供问题的答案。一旦你有足够的钱,你将能够;相反对不起,我不知道,我没有评论的名声。请通过编辑您的答案添加一些解释。。。
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")