繁体   English   中英

如何从变量设置创建文件的名称?

[英]How to set a name of creating file from variable?

我需要使用用户提供的名称作为输入创建一个文件。 例如,如果用户提供值hello那么文件名应该是hello.txt ,这里是创建一个新文件的示例代码。

import os
recipeFileName = input()
currentRecipe = open("fileName.txt", "x")

由于它是一个文本文件,所以请使用w而不是x

recipeFileName = input("Input file Name: ")
currentRecipe = open( recipeFileName + '.txt' , "w")
# insert into file
currentRecipe.close()

open可用于创建文件。(您可以将字符串“fileName.txt”替换为包含该字符串的可验证文件,并为扩展名添加“.txt”

recipeFileName = input()
currentRecipe = open(recipeFileName+'.txt' , "x")

暂无
暂无

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

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