2013-10-08 186 views
2

我正在嘗試將現有文件的每一行寫入兩個新文件。 基本上這將複製文件。 「oldMaster.write(line)」返回一個錯誤,指出該文件不可寫。 我知道我的代碼很糟糕。這是一個項目,我真的被卡住了。無法寫入文件

file_str = input ("Enter a file name: ") 

while True: 
    try: 
     file_obj = open(file_str, 'r') 
     break 
    except IOError: 
     file_str = input("'Invalid file name' Enter a file name: ")   
prefix = input("Master File Prefix?") 
old = prefix 
old += ".old.txt" 
new = prefix 
new += ".new.txt" 
oldMaster = open(old,"w") 
newMaster = open(new,"w") 

oldMaster = file_obj 
newMaster = file_obj 

for line_str in file_obj: 
    line = line_str 

    oldMaster.write(line) 
+2

由於使用未定義的變量'file_obj',該代碼甚至不會運行。 – BrenBarn

+0

什麼是'file_obj',它在那裏做了什麼? –

+0

你能查看文件是否已成功打開? – John

回答

4

您沒有關閉文件,您必須發送commit信號才能寫入文件。

嘗試使用with,其中opens並關閉文件句柄。

with open(old,"w") as oldMaster,open(new,"w") as newMaster: 
+0

如何不使用? – Kecoey

+0

OMG我愛你。我在最後關閉了這些文件,它工作。非常感謝! – Kecoey

0

在你的代碼,file_obj只存在到while。嘗試在while後打印其值。

那麼接下來在打開文件:

>>> oldMaster = open('\users.csv',"w") 

看看什麼oldMaster等於:

>>> oldMaster 
<_io.TextIOWrapper name='\users.csv' mode='w' encoding='cp1251'> 

那麼你ovewrite oldMaster具有可變file_obj,它有一定的價值,但沒有文件:

>>> oldMaster='smthelse' 
>>> oldMaster 
'smthelse' 

所以oldMaster contai n smthelse,不是文件。我想應該刪除while