简体   繁体   中英

How to set a name of creating file from variable?

I need to create a file with the name provided by the user as input. For example, If the user-provided value hello then the file name should be hello.txt , here is a sample code to create a new file.

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

Since it is a text file so pls use w instead of x .

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

open can be used to create a file.(you can just replace the string "fileName.txt" with the veriable containing the string and add '.txt' for the extension

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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