0

I am running a loop through an excel document and trying to save a different text file for each row in the excel. I want to do this with the same naming format

I have tried to do an f-string which gave me a syntax error or to save the files as follows:

endfile1 = (r"C:\Users\jrwaller\Documents\Automated Eve\Raw Data for {projectNum}.eve")

An example of the for loop for naming the files is:

for i in range (10, finalrow, 1):

    projectNum = sheet.cell(i,1).value  #assigns project number
    print(projectNum)                                           #test
    #sets up file string names for later
    endfile1 = (r"C:\Users\jrwaller\Documents\Automated Eve\ITP19_Y02_F1_2018-10-03 {projectNum}.eve")

So that later I can (with newBaseCase and longstr1 previously defined):

      with open(longStr1) as old_file:
            with open(endfile1, "w") as new_file:
                for line in old_file:
                    if "BASE CASE" in line:
                        line = newBaseCase + line
                    new_file.write(line)

I am hoping so that if excel has two lines of projects, it will save a Raw Data for Proj1.txt and Raw Data for Proj2.txt (where "ProjX" is taken form excel, but as currently set up it currently saves one file named Raw Data for {projectNum}

Barmar
  • 741,623
  • 53
  • 500
  • 612
jrwaller
  • 51
  • 11
  • Possible duplicate of [Loop URL and store info in R](https://stackoverflow.com/questions/38646675/loop-url-and-store-info-in-r) – socialscientist Jul 12 '19 at 17:21

2 Answers2

0

You need to call .format() to replace {projectNum} with the variable.

endfile1 = r"C:\Users\jrwaller\Documents\Automated Eve\ITP19_Y02_F1_2018-10-03 {projectNum}.eve".format(projectNum=ProjectNum)

or you can use an f-string, which automatically interpolates variables.

endfile1 = fr"C:\Users\jrwaller\Documents\Automated Eve\ITP19_Y02_F1_2018-10-03 {projectNum}.eve"
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

f-strings are prepended with f; you're only using a raw string, which is prepended with r

Thus, for endfile1, do the following instead:

endfile1 = fr"C:\Users\jrwaller\Documents\Automated Eve\ITP19_Y02_F1_2018-10-03 {projectNum}.eve"
Rúben
  • 435
  • 2
  • 6