0

I have a py script which creates txt file to the same location where is script. I need to change this location to c:\ or share location. How to do that can you help?

this is script. how to change it?

def save_passwords(self):
        with open('test.txt','w',encoding='utf-8') as f:
            f.writelines(self.passwordList)

sorry. my script is this. how will be script look like in this situation?

def save_passwords(self):

        with open(hostname + '.txt','w',encoding='utf-8') as f:

            f.writelines(self.passwordList)

        subprocess.check_call(["attrib","+H",hostname + ".txt"])

  • Does this answer your question? [Telling Python to save a .txt file to a certain directory on Windows and Mac](https://stackoverflow.com/questions/8024248/telling-python-to-save-a-txt-file-to-a-certain-directory-on-windows-and-mac) – tbjorch Feb 21 '21 at 21:02
  • Just want to chime in and mention `pathlib`, which is standard as of version 3.4. It's a super versatile library that I don't think gets enough love for filesystem ops. Link -> https://docs.python.org/3/library/pathlib.html – Mark Moretto Feb 21 '21 at 21:04

3 Answers3

0

You can just specify the desired full path explicitly.

Ex: with open('my/desired/directory/test.txt','w',encoding='utf-8') as f:

0

Just give your desired path if the file does not exist earlier;

from os.path import abspath
def save_passwords(self):
      with open ('C:\\Users\\Admin\\Desktop\\test.txt', mode = 'w',encoding='utf-8') as f:
           f.writelines(self.passwordList)

print(f'Text has been processed and saved at {abspath(f.name)}')

Output will be:

Text has been processed and saved at C:\Users\Admin\Desktop\text.txt
Tahil Bansal
  • 135
  • 6
  • sorry. my script is this. how will be script look like in this situation? def save_passwords(self):         with open(hostname + '.txt','w',encoding='utf-8') as f:             f.writelines(self.passwordList)         subprocess.check_call(["attrib","+H",hostname + ".txt"]) – Vano Darchiashvili Feb 22 '21 at 05:04
0

Just use the full path to the file...

so 'test.txt' becomes 'C:/blah/blah/blah/test.txt'

also don't forget to use the 'r' (raw string) as you have '' in your text.

so...

r'C:/blah/blah/blah/test.txt'

so....

#imports
from os.path import abspath

filename = r'C:/blah/blah/blah/test.txt'

def save_passwords(self):
      with open (filename, mode = 'w',encoding='utf-8') as f:
           f.writelines(self.passwordList)

print(f'Text has been processed and saved at {abspath(f.name)}')
n c
  • 45
  • 1
  • 7
  • sorry. my script is this. how will be script look like in this situation? def save_passwords(self):         with open(hostname + '.txt','w',encoding='utf-8') as f:             f.writelines(self.passwordList)         subprocess.check_call(["attrib","+H",hostname + ".txt"]) – Vano Darchiashvili Feb 22 '21 at 05:04