从raw_input重命名文件

时间:2014-05-20 13:42:46

标签: python file python-2.7 raw-input

我对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'那个?

1 个答案:

答案 0 :(得分:0)

@jonrsharpe在评论中给了你一个很好的答案,但我想我也会给你一些想法,因为看起来你只是想学习新东西......

如果您只想打开文件以向其附加数据,也可以打开(“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])