告诉 Python 将 .txt 文件保存到 Windows 和 Mac 上的某个目录 [英] Telling Python to save a .txt file to a certain directory on Windows and Mac

查看:83
本文介绍了告诉 Python 将 .txt 文件保存到 Windows 和 Mac 上的某个目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何告诉 Python 在哪里保存文本文件?

How do you tell Python where to save a text file?

例如,我的计算机在我的桌面上运行 Python 文件.我希望它将所有文本文件保存在我的文档文件夹中,而不是我的桌面上.我如何在这样的脚本中做到这一点?

For example, my computer is running the Python file off my desktop. I want it to save all the text file in my documents folder, not on my desktop. How do I do that in a script like this?

name_of_file = raw_input("What is the name of the file: ")
completeName = name_of_file + ".txt"
#Alter this line in any shape or form it is up to you.
file1 = open(completeName , "w")

toFile = raw_input("Write what you want into the field")

file1.write(toFile)

file1.close()

推荐答案

打开文件句柄写入时使用绝对路径即可.

Just use an absolute path when opening the filehandle for writing.

import os.path

save_path = 'C:/example/'

name_of_file = raw_input("What is the name of the file: ")

completeName = os.path.join(save_path, name_of_file+".txt")         

file1 = open(completeName, "w")

toFile = raw_input("Write what you want into the field")

file1.write(toFile)

file1.close()

您可以选择将其与 os.path.abspath() 结合使用,如 Bryan 的回答中所述,以自动获取用户文档文件夹的路径.干杯!

You could optionally combine this with os.path.abspath() as described in Bryan's answer to automatically get the path of a user's Documents folder. Cheers!

这篇关于告诉 Python 将 .txt 文件保存到 Windows 和 Mac 上的某个目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆