2014-01-12 18 views
1

我正在試圖從一個文件中讀取一個數字,將它轉換爲一個int值,向其中添加一個數字,然後將新數字重新寫回到該文件中。但是,當我打開.txt文件時,每次運行此代碼時都是空白的。任何幫助,將不勝感激謝謝!我是一個python newb。打開/寫入刪除txt文件內容?

f=open('commentcount.txt','r') 
counts = f.readline() 
f.close 
counts1 = int(counts) 
counts1 = counts1 + 1 
print(counts1) 
f2 = open('commentcount.txt','w') <---(the file overwriting seems to happen here?) 
f2.write(str(counts1)) 

回答

5

存在空文件

此問題是由於您未能關閉文件描述符而導致的。你有f.close但它應該是f.close()(一個函數調用)。最後你還需要一個f2.close()

沒有close它需要一段時間,直到緩衝區的內容到達文件。在不使用文件描述符時儘快關閉文件描述符是一種很好的做法。

作爲一個側面說明,您可以使用下面的語法糖,以保證文件描述符儘快儘可能近:

with open(file, mode) as f: 
    do_something_with(f) 

現在,關於覆蓋部分:

寫入到文件而不會覆蓋以前的內容。

簡短回答:您不以正確的模式打開文件。使用追加模式("a")。


龍回答

這是預期的行爲。閱讀以下內容:

>>> help(open) 
Help on built-in function open in module __builtin__: 

open(...) 
    open(name[, mode[, buffering]]) -> file object 

    Open a file using the file() type, returns a file object. This is the 
    preferred way to open a file. See file.__doc__ for further information. 


>>> print file.__doc__ 
file(name[, mode[, buffering]]) -> file object 

Open a file. The mode can be 'r', 'w' or 'a' for reading (default), 
writing or appending. The file will be created if it doesn't exist 
when opened for writing or appending; it will be truncated when 
opened for writing. Add a 'b' to the mode for binary files. 
Add a '+' to the mode to allow simultaneous reading and writing. 
If the buffering argument is given, 0 means unbuffered, 1 means line 
buffered, and larger numbers specify the buffer size. The preferred way 
to open a file is with the builtin open() function. 
Add a 'U' to mode to open the file for input with universal newline 
support. Any line ending in the input file will be seen as a '\n' 
in Python. Also, a file so opened gains the attribute 'newlines'; 
the value for this attribute is one of None (no newline read yet), 
'\r', '\n', '\r\n' or a tuple containing all the newline types seen. 

所以,在閱讀手冊顯示,如果你想保持的內容,你應該打開追加模式:

open(file, "a") 
0

蟒蛇打開文件paramters:

w

打開文件以只寫。如果文件存在,則覆蓋該文件。 如果文件不存在,則創建一個用於寫入的新文件。

您可以使用a(追加):

打開文件進行追加。如果文件存在,文件指針位於文件末尾 。也就是說,該文件處於追加模式。如果 文件不存在,它將創建一個新文件進行寫入。

獲取更多信息,您可以閱讀here

還有一個建議是使用:

with open("x.txt","a") as f: 
    data = f.read() 
    ............ 

例如:

with open('c:\commentcount.txt','r') as fp: 
    counts = fp.readline() 

counts = str(int(counts) + 1) 

with open('c:\commentcount.txt','w') as fp: 
    fp.write(counts) 

注意:此方法僅當你有一個文件名commentcount它有一個因爲r不會創建新文件,所以它只會有一個計數器,因此它不會附加一個新的數字,因此在第一行是。

+0

您可以打開同一個文件多次。裏面有不同的光標。 –

2

你應該語句中使用。這假設文件描述符無論如何都是關閉的:

with open('file', 'r') as fd: 
    value = int(fd.read()) 

with open('file', 'w') as fd: 
    fd.write(value + 1) 
0

您從不關閉文件。如果您沒有正確關閉文件,操作系統可能不會提交任何更改。爲了避免這個問題,建議您使用Python的with語句來打開文件,因爲它會在您完成文件後關閉它們。

with open('my_file.txt', a) as f: 
    do_stuff()