簡體   English   中英

Python非特定寫入異常

[英]Python non-specific write exception

目前正在自學Python,並通過編寫腳本讀取和添加現有文件來學習文件I / O。 該腳本會一直運行,直到我調用write()方法為止,這時它將拋出一個非特定的異常-這是回溯:

            File "test.py", line 13, in <module>
                f.write(txt)
            IOError: [Errno 0] Error

我的代碼:

            from sys import argv

            script, filename = argv

            f = open(filename, 'a+')

            print("The contents of %s are:") % filename

            print f.read()

            txt = raw_input("What would you like to add? ")

            f.write(txt)

            print("The new contents are:")

            print f.read()

            f.close()

我的環境是Win7,PowerShell和Notepad ++中的Python 2.7.3。

是什么原因造成的? 我該如何解決? 以我的理解, a+訪問模式應允許我讀取並追加到文件。 將訪問模式更改為r+產生相同的異常。

說明:

  • 我有一個帶有單個單詞的現有文本文件(a.txt),我將其作為腳本的參數傳遞,如下所示:

      python test.py a.txt 
  • 我使用Windows中的管理員帳戶。

結果:

至少添加兩個seek()命令可以解決該問題-答案中對此進行了詳細說明。

由於某種原因,當您以a+模式打開文件時,在OS X上print f.read()對我不起作用。

在Max OS X上,將打開模式更改為r+ ,然后在第二次讀取使其f.seek(0)之前添加f.seek(0)行。 可悲的是,這對Windows沒有幫助。

這是Mac OS上的工作代碼:

from sys import argv

script, filename = argv

f = open(filename, 'r+')

print("The contents of %s are:") % filename

print f.read()

txt = raw_input("What would you like to add? ")

f.write(txt)

print("The new contents are:")

f.seek(0)
print f.read()

f.close()

這是我可以在Windows 7上運行的唯一方法:

from sys import argv

script, filename = argv

f = open(filename, 'r')

print("The contents of %s are:") % filename

print f.read()
f.close()

txt = raw_input("What would you like to add? ")

f = open(filename, 'a')
f.write(txt)
f.close()
f = open(filename, 'r')

print("The new contents are:")

print f.read()

f.close()

這似乎超級hacky。 這也應該在Mac OS X上也可以使用。

當嘗試添加小尺寸的文本時出現問題:它保留在緩沖區中,該緩沖區在接收更多數據之后將文本保留在實際寫入之前。
因此,為確保確實編寫,請按照有關os.fsync()flush()的文檔中所述進行操作

順便說一句,最好使用with語句。

而且使用二進制模式更好。 在您的情況下,應該沒有問題,因為您只需在閱讀后添加文本,然后使用seek(o,o) 但是,當想要將文件的指針正確移動到文件的字節中時,絕對有必要使用二進制模式[ open(filename, 'rb+')'b' ]

我個人從來不使用'a+' ,我從不了解它的作用。

from sys import argv
from os import fsync

script, filename = argv

with open(filename, 'rb+') as f:
    print("The contents of %s are:") % filename
    print f.read()

    f.seek(0,2)
    txt = raw_input("What would you like to add? ")
    f.write(txt)
    f.flush()
    fsync(f.fileno())

    f.seek(0,0)
    print("The new contents are:")
    print f.read()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM