2017-09-12 82 views
3

我是編程新手,需要幫助將第一個文件轉換爲另一個文件。任務是:將第一個文件轉換爲另一個文件

編寫一個程序,要求用戶輸入兩個文件名。第一個應該標記任何現有的文本文件。第二個文件名可能是新的,所以具有該名稱的文件可能不存在。

該程序的任務是取出該文件的第一個文件,將其轉換爲大寫字母,並寫入另一個文件。

到目前爲止,我有:

file_old = input("Which file do you want to take ? ") 
file_new = input("In which file do you want to put the content? ") 

file1 = open(file_old, encoding="UTF-8") 
file2 = open(file_new, "w") 

for rida in file1: 
    file2.write(rida.upper()) 

file1.close() 
file2.close() 

The error pic

+3

標題很混亂。你的意思是'file'而不是'fail'? –

+1

失敗是愛沙尼亞語文件 – TemporalWolf

+1

你現在有什麼問題?它怎麼不起作用? – TemporalWolf

回答

2

你必須寫的完整路徑的文件爲您的代碼工作。

我測試了它,它完美地工作。

輸入路徑應

C:\Users\yourUserName\PycharmProjects\test_folder\test_small_letters.txt 

這應該不是你進入

例如old.txt

"C:\Program Files\Python36\python.exe" C:/Users/userName/PycharmProjects/pythonSnakegame/test_file_capitalize.py 
which file you want to take ? C:\Users\userName\PycharmProjects\test_folder\test_small_letters.txt 
In which file you want to put the content? C:\Users\userName\PycharmProjects\test_folder\test_big_letters.txt 
C:\Users\userName\PycharmProjects\test_folder\test_small_letters.txt 
C:\Users\userName\PycharmProjects\test_folder\test_big_letters.txt 

Process finished with exit code 0 

新的文件被創建和資本化。

+0

新用戶(<15代表)不能投票。此外,要求它是可憐的形式。然而,你的答案看起來不錯。 – TemporalWolf

+0

@TemporalWolf,感謝您的建議,只是爲了避免一些嚴重的負面因素,我之前得到的一些問題可能會阻止我詢問......,我注意到她是新人,所以我想向她表明這種好消息,無論誰發現答案有幫助 –

+0

是的,它的工作。謝謝你們^ _^ – Kertrudm

0

您可以通過with聲明以更pythonic的方式執行此操作。這創建了一個上下文管理器,當你完成它時,該管理器會注意到該文件。

file_old = input("Which file do you want to take ? ") 
file_new = input("In which file do you want to put the content? ") 
with open(file_old, 'r') as f1: 
    with open(file_new, 'w') as f2: 
     for line in f1: 
      f2.write(line)   
相關問題