简体   繁体   English

[帮助]从csv文件和output txt(python)中提取[帮助]

[英][Help]Extract from csv file and output txt(python)[Help]

enter image description here在此处输入图像描述

I read the file 'average-latitude-longitude-countries.csv' to the Southern Hemisphere.我将文件“平均纬度经度-countries.csv”读到南半球。

Print the country name of the country in the file 'result.txt'在文件'result.txt'中打印国家的国家名称

Question:问题:

I want you to fix it so that it can be printed according to the image file.我希望您修复它,以便可以根据图像文件打印它。

infile = open("average-latitude-longitude-countries.csv","r")
outfile = open("average-latitude-longitude-countries.txt","w")
joined = []
infile.readline()
for line in infile:
  splited = line.split(",")
  if len(splited) > 4:
    if float(splited[3]) < 0:
      joined.append(splited[2])
      outfile.write(str(joined) + "\n")
  else:
    if float(splited[2]) < 0:
      joined.append(splited[1])
      outfile.write(str(joined) + '\n')

It's hard without posting a head/first few lines of the CSV However, assuming your code works and the countries list is successfully populated.很难不发布 CSV 的头/前几行但是,假设您的代码有效并且国家列表已成功填充。 Then, you can replace the line然后,您可以替换该行

outfile.write(str(joined) + '\n')

with:和:

outfile.write("\n".join(joined))

OR或者

with those 2 lines:用这两条线:

for country in joined:
    outfile.write("%s\n" % country)

Keep in mind, those approaches just do the job.请记住,这些方法只是起到了作用。 however, not optimum然而,不是最佳的

Extra hints:额外提示:

you can have a look at csv module of standard Python.你可以看看标准 Python 的csv模块。 can make your parsing easier可以让你的解析更容易

Also, splited = line.split(",") can lead to wrong output, if there a single quoted field that contains ",".此外, splited = line.split(",")可能会导致错误的 output,如果有一个包含“,”的单引号字段。 like this: field1_value," field 2,value ",field3, field4, ...像这样: field1_value," field 2,value ",field3, field4, ...

Update: Now I got you, First of all you are dumping the whole aggregated array to the file for each line you read.更新:现在我知道了,首先,您要将整个聚合数组转储到您读取的每一行的文件中。 you should keep adding to the array in the loop.您应该继续在循环中添加到数组中。 then after the whole loop, dump in once (Splitting the accumulated array like above)然后在整个循环之后,转储一次(像上面一样拆分累积的数组)

Here is your code slightly modified:这是您的代码稍作修改:

infile = open("average-latitude-longitude-countries.csv","r")
outfile = open("average-latitude-longitude-countries.txt","w")
joined = []
infile.readline()
for line in infile:
  splited = line.split(",")
  if len(splited) > 4:
    if float(splited[3]) < 0:
      joined.append(splited[2])
      #outfile.write(str(joined) + "\n")

  else:
    if float(splited[2]) < 0:
      joined.append(splited[1])
      #outfile.write(str(joined) + '\n')


outfile.write("\n".join(joined))

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

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