2011-08-19 192 views
0

我有一个python代码,我希望它可以创建一个文件,它将导出他想要的文件(用于订单)。我想导出到一个永远不会创建的文件,但我希望它被命名为(客户的名字).txt,例如John Smith.txt,如果他们说那里的名字是john smith。(python)创建一个名称为变量和扩展名的文件

我的工作代码需要你写你的名蟒蛇form.py 后,例如蟒蛇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" 
+0

[使用文件对象](http://diveintopython.org/file_handling/file_objects.html) – Jacob

+0

你尝试了什么?向我们展示迄今为止您的代码。询问我们有关给您带来麻烦的具体部分。不要只是要求我们为你写信。 – agf

+0

我添加了我的代码 – Shameer

回答

3

如果你只是希望创建一个简单的文件具有固定扩展名的变量:

myVar="Joe Smart" 

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

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

+0

感谢你的令人敬畏的作品完美我不相信我没想到现在我感到很蠢:p – Shameer

1

你可能想使用类似mkstemp和/或订单ID添加到文件名,以便2个数量由约翰Smith.txt不覆盖同一个文件。

无论何时你想创建一个原子创建的独特文件,你都需要使用tempfile模块。

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

qor72做得更短,做我需要更好的覆盖不是必要的,但我感谢无论如何我投了 – Shameer

0

这里是一个答案,有乐趣

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

然后,你可以这样做:生成文件( 'Daedalus.so')

+0

对不起,我在找 – Shameer