简体   繁体   中英

converting first file to another file

I'm new at programming and i need help with converting first file to another file. The task is:

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.

So far I have:

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()

错误图片

You have to write the full path to your file for your code to work.

I tested it and it works perfectly.

The input path should be like

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

This should be instead of old.txt that you enter

for example:

"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

The new file was created and capitalized.

You can do that in a more pythonic way, with the with statement. This creates a context manager which takes care to close() the file when you are done with it.

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)        

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM