python导出文件位置更改

2024-09-27 09:37:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这是剧本。如何改变它

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

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

def保存_密码(自身):

将open(hostname+'.txt',w',encoding='utf-8')作为f:

f.writelines(self.passwordList)

子进程。检查_调用([“attrib”、“+H”、主机名+“.txt”])


Tags: pytestselftxt脚本writelinessavedef
3条回答

只需显式指定所需的完整路径即可

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

只需使用文件的完整路径

所以“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)}')

如果文件之前不存在,只需给出所需的路径

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

相关问题 更多 >

    热门问题