Python Forum

Full Version: os library
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm doing a challenge that my code must read lines from a txt file and create others files inside a new directory ,they'll be named with the lines from de first one.
Here is my initial code
import os
with open('C:\\Users\\-\\Desktop\\Python.txt', 'r+') as file:
    countries = list(file.readlines())
    print(countries)
    print(len(countries))
    os.makedirs('C:\\Users\\-\\Documents\\Test', exist_ok=True)
    for lines in countries:
        with open('C:\\Users\\-\\Documents\\Texto\\here.txt') as linhas:
            os.rename('here.txt', 'oi.txt')
But it isn't working, the code return this error:
Error:
Traceback (most recent call last): File "C:/Users/-/PycharmProjects/guppe/teste.py", line 54, in <module> with open('C:\\Users\\-\\Documents\\Texto\\here.txt') as linhas: FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\-\\Documents\\Texto\\here.txt'
How Can i use a loop for getting the names from my file and creat others ?
You most have w to make new files.
with open('C:\\Users\\-\\Documents\\Texto\\here.txt', 'w') as linhas:
But this dos not match what task say as it just create a new file here.txt,
it dos not create others files inside a new directory with names from the first one.
To give a example.
path = r'C:\code\new_folder'
os.makedirs(path, exist_ok=True)
with open('countries.txt') as file:
    for contry in file:
        contry = contry.strip()
        with open(f'{path}/{contry}.txt', 'w') as f_out:
            f_out.write(contry)
So if first line is Norway in countries.txt,it will now name a file Norway.txt with Norway inside placed in new_folder.
Thank you ver much , this advice has helped me a lot .