[英]Saving list from python to text file in format
Say I have a txt file, 说我有一个txt文件,
fantasy,12/03/2014
sci-fi,13/04/2014
history,03/04/2014
And I use the following code to convert it into a python list 我使用以下代码将其转换为python列表
def load_list(filename):
my_file = open(filename, "rU")
my_list = []
for line in my_file:
a,b = line.rstrip("\n").split(",")
my_list.append((as_datetime(b),a))
my_file.close()
return my_list
which outputs [(datetime.datetime(2014, 3, 12, 0, 0), 'fantasy'), (datetime.datetime(2014, 4, 3, 0, 输出[[datetime.datetime(2014,3,12,0,0),'fantasy'),(datetime.datetime(2014,4,3,0,
0), 'history'), (datetime.datetime(2014, 4, 12, 0, 0), 'sci-fi')]. 0),'history'),(datetime.datetime(2014,4,12,0,0),'sci-fi')]。
I can assume that the list will be further modified (appended and removed) while being used. 我可以假定该列表在使用时将被进一步修改(添加和删除)。 My question is, how can I implement a function to export the list as a txt file that followed the formatting of the original file?
我的问题是,如何实现将列表导出为遵循原始文件格式的txt文件的功能?
You can use csv module for reading and writing. 您可以使用csv模块进行读写。
In order to follow the date format, use strptime()
and strftime()
( docs ) from the datetime
module. 为了遵循日期格式,请使用
datetime
模块中的strptime()
和strftime()
( docs )。
Here's a complete example: 这是一个完整的示例:
import csv
from datetime import datetime
FORMAT = '%d/%m/%Y'
def load_list(filename):
my_list = []
with open(filename, "rU") as f:
reader = csv.reader(f)
for line in reader:
my_list.append([line[0], datetime.strptime(line[1], FORMAT)])
return my_list
def save_list(filename, my_list):
with open(filename, "w") as f:
writer = csv.writer(f)
for item in my_list:
writer.writerow([item[0], item[1].strftime(FORMAT)])
my_list = load_list('input.txt')
save_list('output.txt', my_list)
It reads the data from input.txt
and writes it to output.txt
. 它从
input.txt
读取数据并将其写入output.txt
。 After running the script, output.txt
contains the same data as input.txt
: 运行脚本后,
output.txt
包含与input.txt
相同的数据:
fantasy,12/03/2014
sci-fi,13/04/2014
history,03/04/2014
Hope that helps. 希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.