我试图对我的前任制作的python脚本做一个小修改,我遇到了一个问题.我学过编程,但编码不是我的职业.
python脚本处理SQL查询并将它们写入excel文件,有一个文件夹,其中所有查询都以.txt格式保存.该脚本创建一个在文件夹中找到的查询列表,并在for循环中逐个查看.
我的问题是,如果我想在文件夹中重命名或添加查询,我得到一个“[Errno 2]没有这样的文件或目录”错误.该脚本使用相对路径,所以我很困惑为什么它不断为不存在的文件制作错误.
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())
queriesNIC文件夹的内容
> 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.
有没有人有任何建议可能是什么问题?
谢谢
解决方法:
以下方法将是一种改进. 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()
从您提供的示例中,不清楚是否需要进一步访问圆形变量或文件列表.
标签:python