Home > Mobile >  Create text file in folder
Create text file in folder

Time:12-30

I'm trying to create a text file that is named using a variable in my program. Only problem is, I can't specify a directory when i'm naming it using a variable. (vac_postcode is the variable i'm using to name the file)

centrebypostcode = open(C:\Users\Rich\Desktop\Assignment\Centre\vac_postcode   ".txt"', "a ")
            centrebypostcode.write("\n")
            centrebypostcode.write(vac_center)
            centrebypostcode.close()

I'm using "a " because I need the program to create the text file if it doesn't exist, but if it does, it just appends what I need it to, to the text file. (This is my understanding of the usage of "a ")

open(r'C:\Users\Rich\Desktop\Assignment\Centre\vac_postcode ".txt"', "a " ') does not work either, unfortunately. Any help would be appreciated, thank you.

Edit: Thank you everyone, it works. For those of you that downvoted me, I have tried multiple methods before resorting to asking here on Stackoverflow. I wouldn't have asked but I really didn't know. Maybe next time, leave a comment instead of downvoting, I like to leave an upvote on everyone's comments and I can't do it with less than 15. Please be kinder to newbies :))

CodePudding user response:

You have to keep the variable name outside the quoted string, change the line to

centrebypostcode = open(r"C:\Users\Rich\Desktop\Assignment\Centre"   "\\"   vac_postcode   ".txt", "a ")

Edited: the raw string literal cannot have the last backslash, so you need to concatenate that separately.

CodePudding user response:

It looks like that quotation is wrong.

try with this

centrebypostcode = open(r"C:\Users\Rich\Desktop\Assignment\Centre\{}.txt".format(vac_postcode), "a ")

CodePudding user response:

I just try to be more descriptive

filenames = ["my_file1","my_file2"]
for filename in filenames:
    filename = f"C:\Users\Rich\Desktop\Assignment\Centre\vac_postcode\{filename}.txt"
    with open(filename, "a ") as fh:
        fh.write("Hello world")
  • Related