-2

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.

E_net4
  • 27,810
  • 13
  • 101
  • 139
VIMAL RICH
  • 37
  • 6

3 Answers3

2

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.

Anand Sowmithiran
  • 2,591
  • 2
  • 10
  • 22
1

It looks like that quotation is wrong.

try with this

centrebypostcode = open(r"C:\Users\Rich\Desktop\Assignment\Centre\{}.txt".format(vac_postcode), "a+")
cjlee
  • 378
  • 3
  • 10
1

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")
Mazhar
  • 1,044
  • 6
  • 11