請你幫我修改這段代碼,如果這段代碼報錯后,代碼需要自動再次運行
时间: 2024-03-15 15:43:56 浏览: 8
好的,你可以使用 Python 的 `try...except` 语句来实现这个功能。当代码出现异常时,`except` 语句会捕获异常并执行相应的操作,这里我们可以使用一个死循环来实现代码自动再次运行的功能。代码如下:
```
import os
import pandas as pd
import time
while True:
start = time.perf_counter()
try:
def get_txt_files(folder_path):
files = []
for root, dirs, filenames in os.walk(folder_path):
for filename in filenames:
if filename.endswith(".txt"):
files.append(os.path.abspath(os.path.join(root, filename)))
return files
def combine_txt_files(txt_files):
content = ""
for txt_file in txt_files:
with open(txt_file, "r") as f:
content += f.read()
return content
def write_combined_content_to_file(content, file_path):
with open(file_path, "w") as f:
f.write(content)
def txt_to_excel(txt_file, excel_file):
df = pd.read_csv(txt_file, delimiter="\t", header=None)
df.to_excel(excel_file, index=False, header=None)
if __name__=="__main__":
folder_path="Z:\看板v2"
txt_files=get_txt_files(folder_path)
combined_content=combine_txt_files(txt_files)
combined_file_path="D:\\測試log\\TXT合1并.txt"
write_combined_content_to_file(combined_content,combined_file_path)
excel_file_path="D:\\測試log\\123.xlsx"
txt_to_excel(combined_file_path,excel_file_path)
except Exception as e:
print("Error: {}".format(e))
end = time.perf_counter()
print('運行時間為:{}秒'.format(end-start))
time.sleep(30)
```
这样,当代码出现异常时,就会在终端上输出错误信息,然后程序会自动重新运行。