簡體   English   中英

用Python復制文件的這種方法有什么問題?

[英]What's wrong with this method for copying a file in Python?

我不明白為什么我的新文件中包含許多原始文件中沒有的特殊字符。 這類似於“ 學習Python困難的方式”中的 ex17。

#How to copy data from one file into another

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file, to_file)

from_data = open(from_file, "r").read()

print "The input file is %d bytes long" % len(from_data)

print "Checking if output file exist..... %r" % exists(to_file)
print "Hit return to continue or Cntl C to quit"

#keyboard input
raw_input()

out_file = open(to_file, "r+")
out_file.write(from_data)

print "Okay all done, your new file now contains:"
print out_file.read()

out_file.close()

復制時,必須以二進制模式( "rb""wb" )打開文件。

而且,通常最好只使用shutil.copyfile()而不是重新發明這個特定的輪子。 很好地復制文件可能很復雜(我至少有一定權限說 )。

在讀取結果之前,請嘗試使用seek將文件指針倒回到開頭。

out_file = open(to_file, "r+")
out_file.write(from_data)

print "Okay all done, your new file now contains:"
out_file.seek(0)
print out_file.read()

暫無
暫無

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

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