Reputation: 11
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
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
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
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