我正在使用Python 3.6并通过以下代码显示CSV文件的内容:
#!/usr/bin/env python3
import csv
import sys
import json
def main():
try:
with open('file.csv') as csvfile:
readCSV = csv.DictReader(csvfile, delimiter = ',')
for row in readCSV:
print(json.dumps(row))
except Exception as msg:
print(msg)
sys.exit(1)
if __name__ == '__main__':
main()
此代码完美无缺。但是,我注意到当这个代码在linux中运行时,输出从CSV文件以不正确的顺序打印,并且在Windows中运行时,它按预期输出。
我错过了在Linux中正确运行的东西吗?
编辑:
这是Windows的正确输出:
{"First Name": "Bob", "Last Name": "Clay", "Phone": "1234567890", "ID": "4355", "Salary": "899332", "Year": "2002"}
{"First Name": "Mo", "Last Name": "Jo", "Phone": "2848193919", "ID": "1223", "Salary": "872234", "Year": "1998"}
{"First Name": "Steve", "Last Name": "Mann", "Phone": "4732874757", "ID": "1949", "Salary": "75699", "Year": "2015"}
{"First Name": "John", "Last Name": "Smith", "Phone": "1287823408", "ID": "4859", "Salary": "456909", "Year": "1890"}
这是Linux的错误输出:
{"Last Name": "Clay", "Phone": "1234567890", "Year": "2002", "ID": "4355", "Salary": "899332", "First Name": "Bob"}
{"Last Name": "Jo", "Phone": "2848193919", "Year": "1998", "ID": "1223", "Salary": "872234", "First Name": "Mo"}
{"Last Name": "Mann", "Phone": "4732874757", "Year": "2015", "ID": "1949", "Salary": "75699", "First Name": "Steve"}
{"Last Name": "Smith", "Phone": "1287823408", "Year": "1890", "ID": "4859", "Salary": "456909", "First Name": "John"}