Python - [Errno 2] No such file or directory,

4
我正在尝试对我的前任编写的Python脚本进行微小修改,但是我遇到了问题。我学过编程,但编程不是我的专业。
这个Python脚本处理SQL查询并将它们写入Excel文件,有一个文件夹存放所有的查询以.txt格式。该脚本创建一个查询列表,并在for循环中逐个处理。
我的问题是,如果我想重命名或添加一个查询到文件夹中,我会收到"[Errno 2] No such file or directory"错误。该脚本使用相对路径,所以我困惑为什么它会因为不存在的文件而产生错误。
queries_pathNIC = "./queriesNIC/"

def queriesDirer():
    global filelist
    l = 0
    filelist = []
    for file in os.listdir(queries_pathNIC):
        if file.endswith(".txt"):
            l+=1
            filelist.append(file)
    return(l)

问题出现在主函数中:
for round in range(0,queriesDirer()):
    print ("\nQuery :",filelist[round])
    file_query = open(queries_pathNIC+filelist[round],'r'); # problem on this line
    file_query = str(file_query.read())

查询NIC文件夹的内容

  • 00_1_Hardware_WelcomeNew.txt
  • 00_2_Software_WelcomeNew.txt
  • 00_3_Software_WelcomeNew_AUTORENEW.txt

这些脚本可以正常运行,但是如果我将第一个查询的名称更改为“00_1_Hardware_WelcomeNew_sth.txt”或任何其他不同的名称,则会收到以下错误消息:

FileNotFoundError: [Errno 2] No such file or directory: './queriesNIC/00_1_Hardware_WelcomeNew.txt'

我还尝试将新文本文件添加到文件夹中(例如:“00_1_Hardware_Other.txt”),但脚本会跳过处理我添加的所有文件,只使用原始文件。
我正在使用Python 3.4。
有没有人能提出什么可能是问题?
谢谢

1
请参见例如https://dev59.com/B3M_5IYBdhLWcg3wslVW。 - jonrsharpe
你正在使用哪个操作系统? - niyasc
这个脚本是如何运行的?还有其他部分吗?因为filelist是全局变量,很可能在其他地方被修改,甚至在运行之间保存,以避免重新处理已经处理过的文件。 - dhke
1个回答

1
以下方法将是一种改进。使用glob模块可以轻松地生成以.txt结尾的文件列表,而无需创建列表。
import glob, os

queries_pathNIC = "./queriesNIC/"

def queriesDirer(directory):
    return glob.glob(os.path.join(directory, "*.txt"))

for file_name in queriesDirer(queries_pathNIC):
    print ("Query :", file_name)

    with open(file_name, 'r') as f_query:
        file_query = f_query.read()

从您提供的示例中,不清楚您是否需要进一步访问round变量或文件列表。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接