python导出文件位置更改

时间:2021-02-21 20:56:13

标签: python

我有一个 py 脚本,它在脚本所在的相同位置创建 txt 文件。我需要将此位置更改为 c:\ 或共享位置。如何做到这一点,你能帮忙吗?

这是脚本。怎么改?

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

对不起。 我的脚本是这样的。在这种情况下,脚本会是什么样子?

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

3 个答案:

答案 0 :(得分:0)

您可以明确指定所需的完整路径。

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

答案 1 :(得分:0)

如果之前文件不存在,只需给出你想要的路径;

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

输出将是:

Text has been processed and saved at C:\Users\Admin\Desktop\text.txt

答案 2 :(得分:0)

只需使用文件的完整路径...

所以 'test.txt' 变成了 'C:/blah/blah/blah/test.txt'

也不要忘记使用 'r'(原始字符串),因为您的文本中有 ''。

所以...

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

所以....

#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)}')
相关问题