![](/img/trans.png)
[英]Python error “IOError: [Errno 2] No such file or directory” but file is there
[英]Opening a file in python gives the error IOError: [Errno 2] No such file or directory: '' on MAc
我經常為我的任務運行代碼,但這是我第一次在 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。 我在打印語句中添加了括號,並且您的代碼運行完成。 所以也許你想修復打印語句,看看是否有幫助。
我在 VScode 和終端中運行它。 它在兩種情況下都運行完成,沒有錯誤消息。 據我所知,根本沒有輸出。 我想這個腳本在我沒有的另一個文件上運行。 所以我的完成可能不可靠。 但是,我沒有收到任何錯誤消息,所以也許這會告訴您一些信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.