我对python很新,我正在创建一个小脚本,它接受用户的输入并将该数据导出到.txt中,但我希望导出的文件可以根据来自用户的输入。
firstname = raw_input("What is your First Name?" + "\n")
print 'Thank you, %s' % firstname ,
lastname = raw_input("What is your last name?" + "\n")
print 'Thank you %s' % firstname ,'%s' % lastname
age = raw_input("How old are you?" + "\n")
print 'Thank you %s' % firstname , '%s' % lastname
postcode = raw_input("What is your postal code?" + "\n")
print 'Thank you %s' % firstname , '%s' % lastname
jobtitle = raw_input("What is your current Job Title?" + "\n")
print 'Thank you %s' % firstname , '%s' % lastname
file = open("/Users/AshleyRedman/Desktop/Users [CUS] Py27/userinfo.txt", "w")
file.write(firstname +",")
file.write(lastname +",")
file.write(age +",")
file.write(postcode +",")
file.write(jobtitle)
file.close()
在此之后,如何/最佳方式采取'名字'和'姓氏'并重命名文件' user info.txt'那个?
答案 0 :(得分:0)
如果您只想打开文件以向其附加数据,也可以打开(“test.txt”,“a”)。
此外,您可能希望使用csv模块。它可以为您处理解析csv文件。
import csv
....
with open('userinfo.csv', 'wb') as csvfile:
csvwriter= csv.writer(csvfile, delimiter=',')
# write the csv header
csvwriter.writerow('firstname', 'lastname', 'age', 'postcode', 'jobtitle')
# write the data row (often a loop here writing rows of data)
csvwriter.writerow([firstname, lastname, age, postcode, jobtitle])