0

What this does is that it keeps creating a .txt file that keeps duplicating itself in the path that the program is started, here is the code(that works):

import os
import time

file = "1"

while 1 > 0:
   f= open(file + ".txt","a")
   time.sleep(1)
   file += "1"

So what I'm trying to do is that I want to choose a specified path to create and duplicate the (.txt) file instead of the path where the program is started

One of the things that I tried:

import os
import time

file = "1"

while 1 > 0:
   f= open(rC:\Users\PC\Documents\ file + ".txt","a")
   time.sleep(1)
   file += "1"

But didn't work.

Edit:

Last thing I tried was:

import os
import time

file = "1"
path = "r'C:\Users\Daniel\Documents\'"

while 1 > 0:
   f= open(path + file + ".txt","a")
   time.sleep(1)
   file += "1"

But unfortunatley gave me an error that I havent seen in my whole life:

Daniel
  • 103
  • 1
  • 9
  • See for a part of your problem https://stackoverflow.com/questions/4703516/how-to-write-string-literals-in-python-without-having-to-escape-them – Michael Butscher Mar 16 '20 at 13:32
  • 1
    You need quotes for string `"C:\Users\PC\Documents\"+file+".txt"` – xxMrPHDxx Mar 16 '20 at 13:32
  • @xxMrPDDxx I did that but it gives me the error "invalid syntax" at the apostrophe behind the "a" in the same line – Daniel Mar 16 '20 at 13:40
  • Normally, you would add in the directory you want it to go. What do you mean it didn't work, as the should be an error so theres something going wrong in you specifying. – Tommy Lawrence Mar 16 '20 at 15:07

1 Answers1

0

Although there may be other things wrong, at least you should remove excess double quotes around the value you are assigning to path, and the final backslash shouldn't be there anyway because you should use os.path.join(), - so change to:

import os
import time
import os.path

file = "1"
path = r'C:\Users\Daniel\Documents'

while 1 > 0:
   f= open(os.path.join(path, file + ".txt"),"a")
   time.sleep(1)
   file += "1"

A happier alternative might be to switch to forward slashes which python handles quite nicely on Windows:

path = 'C:/Users/Daniel/Documents'