简体   繁体   English

Python打开一个新的.txt文件,保存,然后将文件路径打印到控制台

[英]Python open a new .txt file, save it, and then print the file path to the console

I'm trying to find a way to print out where the below file is saved once my script is run, to the console for the user to see;我正在尝试找到一种方法,在我的脚本运行后将以下文件的保存位置打印到控制台以供用户查看;

from datetime import datetime
import sys

now = datetime.now()
dt_string = now.strftime("%d-%m-%Y--%H.%M.%S")  

fd = open(r'C:\Test-Folder\Test-File'+dt_string+'.txt','w')
old_stdout = sys.stdout   
sys.stdout = fd

print("this is test text")

fd.close()

print("your file has been saved to: ")

Any ideas how i'd go about this?任何想法我会怎么做?

If you are manually giving the path for the file to save it you can directly console the path "path+filename"如果您手动提供文件的路径以保存它,您可以直接控制台路径"path+filename"

if you want to do a check whether the file is saved then you can use the python os module to check whether file exists and print the path of it.如果你想检查文件是否被保存,那么你可以使用 python os module来检查文件是否存在并打印它的路径。

import os
file = open("filename","w+")
// print Absolute path  
if(os.path.exists('filename'):
    print("Your file is saved at:-", os.path.abspath("filename"))

Surely you can just save the filename?你当然可以只保存文件名吗?

filename = r'C:\Test-Folder\Test-File'+dt_string+'.txt'
fd = open(filename,'w')
[ ... ]
print("Your file has been saved to: " + filename)

You can just do:你可以这样做:

fd = open(r'C:\Test-Folder\Test-File'+dt_string+'.txt','w')
print(fd.name)
from pathlib import Path
from datetime import datetime

now = datetime.now()
dt_string = now.strftime("%d-%m-%Y--%H.%M.%S")
filename = Path(Path.home(), 'Test-Folder', f'Test-File_{dt_string}.txt')

print(f"your file has been saved to: {filename}")

Use pathlib使用路径库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM