2014-09-10 39 views
-1

所以我對Python完全陌生,無法弄清楚我的代碼有什麼問題。我的Python代碼有問題(完全初學者)

我需要編寫一個程序,要求輸入現有文本文件的名稱,然後輸入另一個文件的名稱,該名稱不一定需要存在。該程序的任務是獲取第一個文件的內容,將其轉換爲大寫字母並粘貼到第二個文件。然後它應該返回文件中使用的符號數量。

的代碼是:

file1 = input("The name of the first text file: ") 
file2 = input("The name of the second file: ") 
f = open(file1) 
file1content = f.read() 
f.close 
f2 = open(file2, "w") 
file2content = f2.write(file1content.upper()) 
f2.close 
print("There is ", len(str(file2content)), "symbols in the second file.") 

我創建了兩個文本文件,以檢查是否正確的Python執行的操作。原因是文件的長度不正確,因爲我的文件中有18個符號,Python顯示有2個。

您能否幫我解決這個問題?

+1

'f.close'是一個函數,應該調用爲'f.close()',同樣的事情適用於'f2' – randomusername 2014-09-10 14:17:49

+0

非常感謝!還有什麼錯誤? – anya 2014-09-10 14:20:25

+0

爲什麼使用'f2.write()'的返回值就好像它與寫入文件的字符串一樣? – randomusername 2014-09-10 14:20:29

回答

0

問題我看到你的代碼:

  1. close是一個方法,所以你需要使用()操作,否則f.close沒有做什麼你想。
  2. 通常在任何情況下都傾向於使用打開文件的with格式 - 然後在最後自動關閉。
  3. writemethod不返回任何東西,所以file2content = f2.write(file1content.upper())None
  4. 沒有理由在讀取整個文件的內容;如果它是一個文本文件,只是循環遍歷每一行。

(未測試),但我會寫你的程序是這樣的:

file1 = input("The name of the first text file: ") 
file2 = input("The name of the second file: ") 
chars=0 
with open(file1) as f, open(file2, 'w') as f2: 
    for line in f: 
     f2.write(line.upper()) 
     chars+=len(line) 

print("There are ", chars, "symbols in the second file.") 
+0

是否存在'a.txt'?否則,會讀什麼? – dawg 2014-09-10 14:30:54

+0

謝謝,這幫了很多! – anya 2014-09-10 14:38:37

0

input()does not do你所期望的,使用raw_input()代替。

+0

標記爲Python 3,因此[輸入](https://docs.python.org/3.4/library/functions.html?highlight=input#input)正如他所使用的Python 3一樣。 – dawg 2014-09-10 14:31:53

+0

是的,我我正在使用Python 3. – anya 2014-09-10 14:39:27

+0

是的,我應該學習閱讀。 – 2014-09-10 14:51:58