这是代码行:
with open('directory/filename.txt', 'w') as output:
如何制作
filename = input("Write the output file's name :")
为上面的代码工作?
答案 0 :(得分:2)
将带有os.path.join()
的输入文件名加入目录:
import os
filename = input("Write the output file's name: ")
with open(os.path.join('directory', filename), 'w') as output:
# work on file
答案 1 :(得分:1)
您还可以通过直接在open()参数
中输入文件名来创建文件对象 file = open(input("Enter Filename: "),'w')
答案 2 :(得分:0)
>>> with open(input('fname:\n').split('.txt')[0]+'.txt','w') as f:
... f.write('test')
...
fname:
testy
在这种情况下,即使用户输入或未输入文件扩展名,也会添加。
答案 3 :(得分:0)
一种非常基本的方式:
directory = "directory"
filename = input("Name of file")
with open(directory + "/" + filename, "w") as output: # You could also do f"{directory}/{filename}" or use .format
# do_something()
但我更喜欢这样的东西:
with open(pathlib.Path(pathlib.Path(directory) / filename), "w") as output:
# do_something()