2011-08-19 64 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

相關問題