2016-08-03 7 views
0

以下のコードは、ファイルの内容を削除し、ユーザーが端末から入力した新しい文字列を書き込むことを想定しています。すでにそこにある。 truncate()でコンテンツを完全に消去するようには見えません。これはどうすればいいですか?私のコードtruncate()は、古いデータを置き換える代わりに新しいデータを追加します。

:それは本から運動だと私は将来に飛び込むと、任意のより高度なものを使用しないようtruncate()で行う必要があります。 ありがとう!

from sys import argv 
script, filename, user_name = argv 
print("Hi my dear %s... I hope you're doing great today\n" % user_name) 
print("We're going to write a string to a file %r\n" % filename) 
open_file = open(filename, 'r+') 
print("%s, this is what currently file %r has" % (user_name, filename)) 
read_file = open_file.read() 
print("File's content is:\n", read_file) 
quote = "To create, first sometime you need to destroy" 
print("\n\nAs a quote from your favourite movie says: \n\n %r" \ 
    % quote) 
print("So, we will delete the content from the file %r" \ 
    % filename) 
open_file.truncate() 
print("This is the file %r now" % filename) 
print(read_file) 

new_line = input("Now let's write something, please start here... ") 

print("now %s, let's add this line to the same file %r" \ 
    % (user_name, filename)) 
open_file.write(new_line) 
print("Closing the file") 
open_file.close() 
print(read_file) 
open_file.close() 
+0

これ以外にもいくつかの方法がありました。これはおそらく 'open_file.seek(0);の省略形です。 open_file.truncate() '、これは私がいつもしてきたことです。 –

答えて

2

truncate()現在の位置で切り捨てられません。サイズを渡して、ファイルをそのサイズに切り捨てます。

+0

Gracias Ignacio – kuatroka

1

メソッドは、省略可能なsize引数を持ちますが、これはデフォルトではファイルポインタの現在の位置です。ファイル上で既にreadを呼び出しているので、現在の位置はファイルの末尾なので、truncateは何もしません。

電話をtruncate(0)に変更すると、ファイルが消去されます。

+0

ありがとうtzaman、私は(0)を追加し、期待どおりに機能しました。私はポインタと必要なファイルサイズを知らなかった – kuatroka

関連する問題