Home > Software design >  how can i create a new file in a for loop
how can i create a new file in a for loop

Time:01-25

for name in names:
    with open(f"/Users/XYZ/Desktop/technology/z 100 days of code z/python/Day 24 Mail Merge Project Start/Mail Merge Project Start/Output/ReadyToSend/new.txt") as file:
        final = letter
        final.replace("[name]", name)
        file.write(final)

trying to create a new file for each name in the list of names, but it doesn't work. getting the below error. thanks.

OSError: [Errno 22] Invalid argument: '/Users/XYZ/Desktop/technology/z 100 days of code z/python/Day 24 Mail Merge Project Start/Mail Merge Project Start/Output/ReadyToSend/Aang\n.txt'

was expecting that a new file would be created for each name. am i doing it wrong or is there a different way of achieving what i'm expecting.

CodePudding user response:

You need to replace the name of the file before creating it:

filename = f"/Users/XYZ/Desktop/technology/z 100 days of code z/python/Day 24 Mail Merge Project Start/Mail Merge Project Start/Output/ReadyToSend/new.txt"
for name in names:
    with open(filename.replace("new", name), "w") as file:
        file.write("test")

CodePudding user response:

  1. Make sure the file path is valid. (Including C:\ if you're on windows)
  2. Specify the mode in which you want to open the file, you are opening it in read mode.
  3. You're not creating a new file, you're opening the same one, you need to specify a different path.

https://docs.python.org/3/library/functions.html#open

  • Related