[英]How to read in a text file, create a dictionary, read in another text file and translate it with said dictionary and write it into a new file
[英]Read Dictionary and write to a text file
我现在有字典:
data = [{'position': 1, 'name':'player1:', 'number': 524}, {'position':2, 'name': 'player2:','number': 333}]
(首先列出两个数字组以简化问题)我想按以下位置顺序阅读和打印:文本或csv文件中的“位置1”,“位置2” ...“位置n”。
就像是:
position name number
1 player1 524
2 player2 333
我试过了:
data = [{'position': 1, 'name':'player1', 'number': 524}, {'position':2, 'name': 'player2:','number': 333}]
keys = data[0].keys()
with open(output.csv", 'r') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(data)
似乎我应该创建一个csv而不是先打开它。 另外,还有什么更好的方法吗? 谢谢。
最简单的操作可能是将其读取到pandas Dataframe中,然后将其写入csv。
import pandas as pd
data = [
{
'position': 1,
'name':'player1',
'number': 524
}, {
'position': 2,
'name': 'player2',
'number': 333
}
]
df = pd.DataFrame.from_records(data, columns=['position', 'name', 'number'])
df = df.sort_values('position')
df.to_csv('data.csv')
使用熊猫
import pandas as pd
data = [
{
'position': 1,
'name':'player1:',
'number': 524
}, {
'position':2,
'name':'player2:',
'number': 333
}
]
df = pd.DataFrame.from_records(data, columns=['position', 'name', 'number'])
df = df.sort_values('position')
df.head()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.