2011-02-24 63 views
3

我遇到了一個非常奇怪的錯誤。Python - 無效模式('w')或文件名

我有我的python腳本的代碼作爲我的很多功能的一部分:

url=['http://agecommunity.com/query/query.aspx?name=', name, '&md=user'] 
url=''.join(url) 
file = open("QueryESO.xml", "w") 
filehandle = urllib.urlopen(url) 
for lines in filehandle.readlines(): 
    file.write(lines) 
file.close() 

當我在怠速運轉,一切都很正常。

如果我與Python(命令行)運行它,然後它給了我這個錯誤:

[Errno 22] invalid mode('w') or filename: 'QueryESO.xml'

在此處,它開始變得怪異: 古怪#1:我有不同的功能完全相同的代碼在我的腳本中,但錯誤只發生在其中一個。

古怪#2:如果我修改代碼,這一點,它工作正常:

url=['http://agecommunity.com/query/query.aspx?name=', name, '&md=user'] 
print url 
url=''.join(url) 
file = open("QueryESO.xml", "w") 
filehandle = urllib.urlopen(url) 
for lines in filehandle.readlines(): 
    file.write(lines) 
file.close() 

我也嘗試打印網址移動到後我加入了名單,其中沒有工作,我只是嘗試打印「」,這也得到了前面提到的錯誤。

所以我想我已經找到了解決方案......但任何人都可以解釋這種行爲?難道我做錯了什麼? (那你需要我張貼,所以你可以亂整個腳本呢?)

編輯:這裏是整個代碼:

import urllib 
from Tkinter import * 
import tkFont 
master = Tk() 

QUERY_ESO = "QueryESO.xml" 

def QueryXML(xml, attribute): 
    x = ["<", attribute, ">"] 
    x=''.join(x) 
    z = xml.split(x, 1) 
    x = ["</", attribute, ">"] 
    x=''.join(x) 
    z=z[1] 
    z=z.split(x, 1) 
    return z[0] 

def AddFriend(): 
    nfentry = nfe2 
    name=nfentry.get() 
    url=['http://agecommunity.com/query/query.aspx?name=', name, '&md=user'] 
    url=''.join(url) 
    file = open("QueryESO.xml", "w") 
    filehandle = urllib.urlopen(url) 
    for lines in filehandle.readlines(): 
     file.write(lines) 
    file.close() 
    f = open(QUERY_ESO, "r") 
    xml = f.readlines() 
    f.close() 
    xml=''.join(xml) 
    f = open("Friends.txt", "r") 
    filestring = f.read() 
    f.close() 
    fs = filestring.split('\n') 
    if name in fs: 
     print "Friend Already Added" 
    elif xml == "<?xml version='1.0' encoding='utf-8'?><error>Failed to find user</error>": 
     print "User does not exist" 
    else: 
     fs.append(name) 
     fs = '\n'.join(fs) 
     f = open("Friends.txt", "w") 
     f.write(fs) 
     f.close() 
    nfe2.set("") 
    nfentry = nfe2 

def DeleteFriend(): 
    ofentry = ofe2 
    name=ofentry.get() 
    f = open("Friends.txt", "r") 
    filestring = f.read() 
    f.close() 
    fs = filestring.split('\n') 
    if name in fs: 
     fs.remove(name) 
     fs = '\n'.join(fs) 
     f = open("Friends.txt", "w") 
     f.write(fs) 
    ofe2.set("") 
    ofentry = ofe2 

def IsOnline(name): 
    url=['http://agecommunity.com/query/query.aspx?name=', name, '&md=user'] 
    print url 
    url=''.join(url) 
    file = open("QueryESO.xml", "w") 
    filehandle = urllib.urlopen(url) 
    for lines in filehandle.readlines(): 
     file.write(lines) 
    file.close() 
    f = open(QUERY_ESO, "r") 
    xml = f.readlines() 
    f.close() 
    xml=''.join(xml) 
    if xml == "<?xml version='1.0' encoding='utf-8'?><error>Failed to find user</error>": 
     print "User does not exist" 
    else: 
     datetime = QueryXML(xml, "LastUpdated") 
     datetime = datetime.split('T', 1) 
     time = datetime[1].split('Z', 1) 
     date = datetime[0] 
     print "User", name, "is", QueryXML(xml, "presence"), "as of", date, "at", time[0] 
     return QueryXML(xml, "presence") 

def FriendCheck(): 
    f = open("Friends.txt", "r") 
    filestring = f.read() 
    f.close() 
    fs = filestring.split('\n') 
    Laonline = Label(lowerframe, text="") 
    Laonline.grid(column=0, row=0) 
    Laonline.grid_forget() 
    x=0 
    while x <= (len(fs)-1): 
     if IsOnline(fs[x]) == "online": 
      Laonline = Label(lowerframe, text=fs[x]) 
      Laonline.grid(column=0, row=x) 
     x=x+1 

def RunTwo(Function1, Function2): 
    Function1() 
    Function2() 

def DeleteAllFriends(): 
    fs = "<?xml version='1.0' encoding='utf-8'?>\n<friends>\n</friends>" 
    f = open("Friends.txt", "w") 
    f.write(fs) 
    f.close() 
    FriendCheck() 

def DAFPop(): 
    DAFpopup = Toplevel() 
    DAFframe = Frame(DAFpopup) 
    DAFframe.grid(columnspan=4, column=0, row=0) 
    F1 = DeleteAllFriends 
    F2 = DAFpopup.destroy 
    Q1 = lambda: RunTwo(F1, F2) 
    DAFL1 = Label(DAFframe, text="This delete all of your friends. Are you sure you wish to continue?") 
    DAFL1.grid() 
    DAFOK = Button(DAFpopup, width=10, text="Yes", command=Q1) 
    DAFOK.grid(column=1, row=1) 
    DAFNO = Button(DAFpopup, width=10, text="No", command=DAFpopup.destroy) 
    DAFNO.grid(column=2, row=1) 

frame = Frame(master, bd=5) 
frame.grid() 

friendlist = Frame(frame, bd=5, width=150, height=400) 
friendlist.grid(column=0, row=0, rowspan=15) 

lon = Frame(friendlist, bd=2, width=150, height=10) 
lon.grid() 

Lonline = Label(lon, text="Friends Online") 
Lonline.grid(column=0, row=1) 
underlined = tkFont.Font(Lonline, Lonline.cget("font")) 
underlined.configure(underline=True) 
Lonline.configure(font=underlined) 

lowerframe = Frame(friendlist, bd=2, width=150, height=390) 
lowerframe.grid() 

lowerframe.grid_propagate(0) 

newfriendframe = Frame(frame, bd=2) 
newfriendframe.grid(column=1, row=0) 

nfe2 = StringVar() 
nfentry = Entry(newfriendframe, width=12, textvariable=nfe2) 
nfentry.grid() 
nfe2.set("") 
nfentry = nfe2.get() 

newfriend = Button(newfriendframe, text="Add Friend", width=10, command=AddFriend) 
newfriend.grid(column=0, row=1) 

oldfriendframe = Frame(frame, bd=2) 
oldfriendframe.grid(column=1, row=1) 

ofe2 = StringVar() 
ofentry = Entry(oldfriendframe, width=12,textvariable=ofe2) 
ofentry.grid() 
ofe2.set("") 
ofentry = ofe2.get() 

oldfriend = Button(oldfriendframe, text="Delete Friend", width=10, command=DeleteFriend) 
oldfriend.grid(column=0, row=1) 

rof = Button(frame, text="Reset List", width=10, command=DAFPop) 
rof.grid(column=1, row=2) 

update = Button(frame, text="Refresh", width=10, command=FriendCheck) 
update.grid(column=1, row=3) 

close = Button(frame, text="Exit", width=10, command=master.destroy) 
close.grid(column=1, row=4) 

master.mainloop() 

,這是不工作的功能IsOnline() ,儘管我已經在那裏爲我貼的代碼留下了打印url,這似乎使它在90%的時間內沒有錯誤地運行,而如果沒有它,它會在100%的時間內得到錯誤。

它也具有相關的文本文件,Friends.txt:

zorc17 
WilliamWallace30 
Sir_Constantin 
jerom_the_brave 
elvarg_flame 
refinedchaos 
Metis 
Lancener 
Neverseperat 
musketeer925 
maxulino 
Zack_iz_Weird 
StormComing 

這似乎創造QueryESO.xml對我蠻好,即使它不存在(當它不出現錯誤, 當然)。如果不是這種情況,名爲QueryESO.xml的空白文件將正常工作,因爲它從網頁獲取其內容。

「刷新」按鈕是其中存在錯誤的按鈕。

+4

'file'是Python中內置文件類型的名稱;重寫它被認爲是不好的做法。 – katrielalex 2011-02-24 22:01:29

+0

代碼實際上自己指定「QueryESO.xml」,對嗎? (前面沒有路徑/目錄?) – user470379 2011-02-24 22:16:08

+0

我發佈的代碼正是我腳本中的代碼...所以前面沒有任何路徑或目錄。這是有效的,因爲該文件位於相同的目錄中(對嗎?)。 和@katrielalex: 我一定會改變它覆蓋內置的文件名。 – 2011-02-24 22:52:04

回答

3

一些觀察:

(1)如果該問題是在實際文件名無效字符,這將是從錯誤消息明顯;見下圖:

>>> open('fu\x01bar', 'w') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
IOError: [Errno 22] invalid mode ('w') or filename: 'fu\x01bar' 

(2)你說你正在使用的文件名一個全局常量,但也有兩次出現的文字文本的(在功能AddFriend和IsOnline) - 它幫助,如果你做確保您發佈的代碼實際上是您運行的代碼。

(3)這種「工作90%的時間」行爲的一個原因是擴展(例如,tkinter)沒有處理異常,然後當別的東西檢查錯誤時彈出。請注意,對於errorno 22,Windows只報告「發生了某種惡行」,並且Python必須發出「哦,在這種情況下,模式必須錯誤,或者文件路徑必須是錯誤的」錯誤消息。 (4)我不是一個擺脫困惑的人,但是:在兩個地方你從網上得到結果,把它們寫到這個文件中,然後讀回來 - 爲什麼?你爲什麼不直接在內存中使用Web結果?

+1

......我真的不知道我爲什麼這麼做。我沒有一個合法的理由。我只是讓它工作。有時候我只是沒有想到這些東西;這真的只是我寫的第三個合法的程序,所以我有點新手。我會試着從內存中讀取結果。 – 2011-02-26 15:20:46

+0

我這樣做,原因是我上傳一個文件調整大小,然後上傳到s3亞馬遜。我收到了同樣的錯誤。 http://stackoverflow.com/questions/17467967/invalid-filename-or-mode-wb – Sohaib 2013-07-04 11:07:48

+0

我遇到同樣的問題,也「工作90%的時間」。我將命令行的輸出記錄到文件中。我創建了幾個文件來記錄不同命令的輸出。我想這可能是問題發生的原因。 – 2014-02-13 21:54:21

0

由於'w'是一個有效的模式,問題在於文件名。也許你在一個上下文中不使用相同的系統編碼。如果它只在一個函數中,那麼在這個文件名實例中可能有一些隱藏字符。解決這個問題的第一步是將文件名設置爲模塊級常量。

+0

我將文件名改爲一個常量,但它仍然存在,因爲它不在一個模塊中工作,而它仍然在其他模塊中工作。 它只是困擾我爲什麼簡單地列印名單,網址,修復問題。 – 2011-02-24 23:05:41

+0

@user好吧,這可能是因爲它引入了延遲,或者是因爲它導致某種I/O緩衝區刷新,或者類似的,我猜。如果你進行「睡眠(1)」而不是打印,會發生什麼? ('進口時間'第一...) – 2011-02-25 15:05:54

+0

@Matt呃...我現在試着用睡覺,當我把睡眠(1),它給了我錯誤,NameError:全球名稱'睡眠'不是定義,我也試過time.sleep(1),它告訴我:UnboundLocalError:賦值之前引用的局部變量'time'。 我沒有導入時間...當在另一個文件中使用導入時間和time.sleep(1)時,它工作正常......我不確定我在做什麼錯了? – 2011-02-25 16:10:27

相關問題