
Python程序重复运行无响应的排查与修复
本文分析一个Python程序在第二次运行时无响应的问题,该程序旨在批量处理指定目录下的多个文件。
问题现象
程序第一次运行正常,但第二次运行时却没有任何反应,程序卡死。
立即学习“Python免费学习笔记(深入)”;
代码片段及问题所在
提供的代码片段中,get_file(files) 函数负责批量处理文件,但该函数调用被遗漏了。 print('ok') 语句之后应该添加 get_file(files) 来完成文件处理。 此外,get_file 函数内部存在逻辑错误,需要修正。
<code class="python">import os
import re
import csv
aa_codes = {'ala':'a','cys':'c','asp':'d','glu':'e',
'phe':'f','gly':'g','his':'h','lys':'k','ile':'i',
'leu':'l','met':'m','asn':'n',
'pro':'p','gln':'q','arg':'r',
'ser':'s','thr':'t','val':'v','tyr':'y','trp':'w'}
def file_name(files):
lst = []
files = os.listdir(file_dir)
for file in files:
lst.append(file)
return lst
file_dir='d:\python代码\new - 副本' # 请确保此路径正确
files=file_name(file_dir)
#对文件进行批量操作
def get_file(files):
for file in files:
try:
with open(os.path.join(file_dir, file), 'r') as f: # 使用os.path.join避免路径问题
txts = f.readlines()
# ... (此处代码逻辑有误,需要修正,见下文) ...
except Exception as e:
print(f"Error processing file {file}: {e}")
# ... (修正后的get_file函数逻辑,见下文) ...
print('ok')
get_file(files) # 添加get_file函数调用</code>get_file 函数逻辑修正
原代码中get_file函数的逻辑存在错误,特别是处理重复行和CSV写入的部分。以下提供修正后的代码:
<code class="python">def get_file(files):
for file in files:
try:
with open(os.path.join(file_dir, file), 'r') as f:
txts = f.readlines()
# 去除重复行
unique_txts = []
for line in txts:
if line not in unique_txts:
unique_txts.append(line)
res1 = []
for line in unique_txts:
parts = re.split(r's*,s*', line.strip()) # 使用更稳健的分割方式
if len(parts) >= 6 and parts[3] in aa_codes: # 增加判断条件避免索引错误
res1.append(aa_codes[parts[3]])
with open(os.path.join(file_dir, file + '.csv'), 'w', newline='') as csvfile: # 添加newline=''避免空行
writer = csv.writer(csvfile)
writer.writerow(res1)
except Exception as e:
print(f"Error processing file {file}: {e}")
</code>总结
程序无响应的原因是缺少 get_file(files) 函数调用以及 get_file 函数内部逻辑错误。 通过添加函数调用并修正函数内部逻辑,程序可以正常重复运行并批量处理文件。 请确保 file_dir 路径设置正确,并检查文件内容是否符合预期格式。 添加错误处理机制可以提高程序的健壮性。
以上就是Python程序重复运行无反应:如何解决批量文件处理程序在第二次运行时无响应的问题?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号