(python) make a file that has a name of a variable and an extension [closed]
I have a python code and i want it to make a file where it exports what the person wants(for a order). I want to export to a file never created but i want it to be named (the costumer's name).txt for example John Smith.txt if they said there name was john smith.
My working code requires you to write your filename after python form.py for example python form.py test.txt would write what the user specified as their info What i want is the file name to be their name and add the extension .txt here is my code that works
from sys import argv
file_name, script = argv
print "Hello I will now ask you for your information.\n"
print "What is your name (last first)?"
name = raw_input()
print "Alright, what is your adderess? "
address = raw_input()
print "Phone Number"
number = raw_input()
print "Email"
email = raw_input()
print "fax"
fax = raw_input()
print "Thank you now I will ask you for you vehicle information.\n"
print "开发者_JAVA百科Year"
year = raw_input()
print "Make"
make = raw_input()
print "Model"
model = raw_input()
print "Mileage"
mileage = raw_input()
print "vin number"
vin = raw_input()
print "Thank you processing information"
target = open ("file_name", 'w')
target.write("Information for ")
target.write(name)
target.write("\n")
target.write("name: ")
target.write(name)
target.write("\n")
target.write("Address: ")
target.write(address)
target.write("\n")
target.write("Phone Number: ")
target.write(number)
target.write("\n")
target.write("Email: ")
target.write(email)
target.write("\n")
target.write("Fax: ")
target.write(fax)
target.write("\n")
target.write("\n")
target.write("Vehicle information")
target.write("\n")
target.write("Year: ")
target.write(year)
target.write("\n")
target.write("Make: ")
target.write(make)
target.write("\n")
target.write("Model: ")
target.write(model)
target.write("\n")
target.write("Mileage: ")
target.write(mileage)
target.write("\n")
target.write("Vin Number: ")
target.write(vin)
target.close()
print "Ok done saved info."
print "\n"
If you're just looking to create a simple file from a variable with a fixed extension:
myVar="Joe Smart"
x = open (myVar+".txt", "w")
x.write("hello")
x.close()
Creates Joe Smart.txt
in the current directory. You'd want to do better error checking than I did.
You probably want to use something like mkstemp and/or add an order id to the filename so that 2 orders by John Smith.txt don't overwrite the same file.
Whenever you want to an unique file created atomicly you'll want to use the tempfile module.
import tempfile
filehandle, absolute_path = tempfile.mkstemp(suffix=user.full_name + ".txt")
Here is an answer, have fun
def MakeFile(file_name):
temp_path = 'C:\\Python3\\' + file_name
file = open(temp_path, 'w')
file.write('')
file.close()
print 'Execution completed.'
Then you can do: MakeFile('Daedalus.so')
精彩评论