Vano Darchiashvili
Vano Darchiashvili

Reputation: 11

python export file location change

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"])

Upvotes: 0

Views: 993

Answers (3)

n c
n c

Reputation: 45

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)}')

Upvotes: 0

Tahil Bansal
Tahil Bansal

Reputation: 163

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

Upvotes: 0

Garrett Souza
Garrett Souza

Reputation: 46

You can just specify the desired full path explicitly.

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

Upvotes: 0

Related Questions