[英]create file after positive exception FileNotFoundError
I have written script that parses a web page and saves data of interest in a CSV file. 我已经编写了用于解析网页并将脚本中感兴趣的数据保存在CSV文件中的脚本。 Before I open the data and use it in a second script I check if the file with data exist and if not I am running the parser script first.
打开数据并将其用于第二个脚本之前,请检查包含数据的文件是否存在,如果不存在,请首先运行解析器脚本。 The odd behaviour of the second script is, that it is able to detect that there is no file, then the file is created, but when it is read for the first time it is empty (part of else statement).
第二个脚本的奇怪行为是,它能够检测到没有文件,然后创建了文件,但是当第一次读取文件时,它是空的(else语句的一部分)。 I tried to provide some delay by using the time.sleep() method, but it does not work.
我试图通过使用time.sleep()方法提供一些延迟,但是它不起作用。 The explorer clearly shows that the file is not empty, but at the first run, script recognizes the file as empty.
资源管理器清楚地表明该文件不为空,但是在第一次运行时,脚本会将文件识别为空。 At the subsequent runs the scripts clearly sees the file and is able to properly recognize it content.
在随后的运行中,脚本可以清楚地看到文件并能够正确识别其内容。
Maybe You have some explanation for this behaviour. 也许您对此行为有一些解释。
def open_file():
# TARGET_DIR and URL are global variables.
all_lines = []
try:
current_file = codecs.open(TARGET_DIR, 'r', 'utf-8')
except FileNotFoundError:
procesed_data = parse_site(URL)
save_parsed(procesed_data)
compare_parsed()
open_file()
else:
time.sleep(10)
data = csv.reader(current_file, delimiter=';')
for row in data:
all_lines.append(row)
current_file.close()
return all_lines
You got some recursion going on. 您正在进行一些递归。
Another way to do it—assuming I understand correctly—is this: 假设我理解正确,另一种方法是:
import os
def open_file():
# TARGET_DIR and URL are global variables.
all_lines = []
# If the file is not there, make it.
if not os.path.isfile(TARGET_DIR):
procesed_data = parse_site(URL)
save_parsed(procesed_data)
compare_parsed()
# Here I am assuming the file has been created.
current_file = codecs.open(TARGET_DIR, 'r', 'utf-8')
data = csv.reader(current_file, delimiter=';')
for row in data:
all_lines.append(row)
current_file.close()
return all_lines
you should return the result of your internal open_file
call, or just opening the file in your except block: 您应该返回内部
open_file
调用的结果,或者只是在您的except块中打开文件:
def open_file():
# TARGET_DIR and URL are hopefully constants
try:
current_file = codecs.open(TARGET_DIR, 'r', 'utf-8')
except FileNotFoundError:
procesed_data = parse_site(URL)
save_parsed(procesed_data)
compare_parsed()
current_file = codecs.open(TARGET_DIR, 'r', 'utf-8')
data = csv.reader(current_file, delimiter=';')
all_lines = list(data)
current_file.close()
return all_lines
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.