我经常为我的任务运行代码,但这是我第一次在Mac上运行它并且它给了我错误 -
Traceback (most recent call last):
File "bt.py", line 103, in <module>
with open(filename,"a") as fout:
NameError: name 'filename' is not defined
代码是 -
import time
from datetime import datetime, timedelta
import re
import zipfile
import glob, os
import string
str=""
new_name=""
new_name1=""
date_folder_name=""
flag=0
file_name=""
file_name2=""
filename=""
line2=""
lines=""
i=0
path=""
clock=""
device=""
command=""
commandName=""
data=""
#..\input\BT
inputBTFolder=os.path.join('..','input','BT')
#Extracting Zip File and Storing Date
for root, dirs, files in os.walk(inputBTFolder):
for file in files:
if '.zip' in file:
print("Processing:"+file)
file_name=file.split('.zip')[0]
file_name2=file_name.split('_')
zip=zipfile.ZipFile(os.path.join(inputBTFolder,file))
zip.extractall(os.path.join(inputBTFolder,file.split('.zip')[0]))
year='20'+file_name2[6]
month=file_name2[5]
date=file_name2[4]
Date=date+"-"+month+"-"+year
dateformat=datetime.strptime(Date,'%d-%m-%Y')
clock=dateformat.strftime("%Y%m%d")+"000000"
for root, dirs, files in os.walk(os.path.join(inputBTFolder,file_name)):
for file in files:
f=open(os.path.join(root,file), "r")
for line in f:
crInfo='CR INFO'
#i=0
if 'Connecting to ' in line :
deviceName=line.split(" ")
device=deviceName[2]
print device
path=os.path.join('..','output','British-Telecom','cli',clock,device)
if os.path.exists(path):
continue
else :
os.makedirs(path)
#Code for each device starts from here -
if 'executing' in line:
commandName=line.split("'")
command=commandName[1]
if ("/" or "*" or ":" or "%" or "-" or "|" or " " in command) :
if("|" in command):
commandname1=command.split("|")
command=commandname1[0]
command=command.replace("/", "_")
command=command.replace("*", "_")
command=command.replace(":", "_")
command=command.replace("%", "_")
command=command.replace("-", "_")
command=command.replace(" ", "_")
if("__" in command):
command=command.replace("__", "_")
if(len(command)>0 and command[-1]=='_'):
command=command[:-1]
filename=path+"/"+command+".txt"
open(filename,'a').close()
if crInfo not in line:
with open(filename,"a") as fout:
fout.write(line)
能不能让我知道我在Mac上看到的问题是什么,我该如何解决?
我刚刚在iMac上尝试了你的文件,但它没有完成。它为第58行提供了一条错误消息,即语句print device
。 Python 3及更高版本要求print语句有括号,所以你的行应该是print (device)
。您运行它的另一台计算机可能使用了python 2,而Mac可能正在使用python3。我在print语句中添加了括号,代码运行完成。所以也许你想修复print语句,看看是否有帮助。
我在VScode中运行它,也从终端运行它。它在两种情况下都运行完成,没有错误消息。据我所知,根本没有输出。我想这个脚本运行在我没有的另一个文件上。所以我的完成运行可能不可靠。但是,我没有收到任何错误消息,所以可能会告诉你一些事情。