将第一个文件转换为另一个文件

2024-04-25 12:13:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新的编程,我需要帮助转换第一个文件到另一个文件。任务是:

Write a program that asks the user for two filenames. The first one should mark any existing text file. The second filename may be new, so the file with this name may not exist.

The program's task is to take the first file of the file, convert it to capital letters, and write another file.

到目前为止,我已经:

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


Tags: 文件thetonewforprogramfile1old
2条回答

您可以使用with语句以一种更为python的方式来实现这一点。这将创建一个上下文管理器,当您处理完文件时,它将负责close()该文件。你知道吗

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)        

为了使代码正常工作,必须编写文件的完整路径。你知道吗

我测试过了,效果很好。你知道吗

输入路径应该是

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

新文件已创建并大写。你知道吗

相关问题 更多 >