(python)创建一个具有变量名称和扩展名的文件

时间:2011-08-19 11:39:19

标签: python file

我有一个python代码,我想让它创建一个文件,导出人们想要的东西(订单)。我想导出到一个从未创建过的文件,但是我希望它被命名(客户名称).txt,例如John Smith.txt,如果他们说名字是john smith。

我的工作代码要求你在python form.py之后编写你的文件名 例如python form.py test.txt会写出用户指定的信息 我想要的是文件名作为他们的名字,并添加扩展名.txt 这是我的代码

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 "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"

3 个答案:

答案 0 :(得分:3)

如果您只是想从具有固定扩展名的变量创建一个简单文件:

myVar="Joe Smart"

x = open (myVar+".txt", "w")
x.write("hello")
x.close()

在当前目录中创建Joe Smart.txt。你想做比我更好的错误检查。

答案 1 :(得分:1)

您可能希望使用类似mkstemp的内容和/或向文件名添加订单ID,以便John Smith.txt的2个订单不会覆盖同一个文件。

每当你想要一个原始创建的唯一文件时,你就会想要使用tempfile模块。

import tempfile
filehandle, absolute_path = tempfile.mkstemp(suffix=user.full_name + ".txt")

答案 2 :(得分:0)

这是一个答案,玩得开心

def MakeFile(file_name):
    temp_path = 'C:\\Python3\\' + file_name
    file = open(temp_path, 'w')
    file.write('')
    file.close()
    print 'Execution completed.'

然后你可以这样做:MakeFile('Daedalus.so')