简体   繁体   English

从raw_input重命名文件

[英]Rename a file from the raw_input

I am quite new to python in general and I am creating a small script that takes the input from a user and exports that data into a .txt, however I would like the exported file to be auto renamed based upon on of the inputs from the user. 一般而言,我对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()

After this, how / what is the best way to take the 'firstname' and 'lastname' and rename the file 'user info.txt' to that? 之后,如何/最好的方式是采用“名字”和“姓氏”并将文件“ user info.txt”重命名为?

@jonrsharpe gave you a good answer in the comments, but I thought I'd also give you some ideas since it looks like you are just trying to learn new things... @jonrsharpe在评论中给了您一个很好的答案,但我想我也会给您一些想法,因为看起来您只是在尝试学习新事物...

You can also do open("test.txt", "a") if you just want to open the file up to append data to it. 如果您只想打开文件以向其追加数据,也可以执行open(“ test.txt”,“ a”)。

Also you might like to look at using the csv module. 另外,您可能希望使用csv模块。 It can handle parsing csv files for you. 它可以为您处理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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM