2017-01-29 100 views
0

我读巨大的csv文件,并采取日期和时间的最后一行。 我写下面的代码,寻找增强或优化的解决方案。Python 3的读写csv文件,并使用字典打印行

以下是我的数据:

2067458,XXXXXXXXXX,1006386,100.79.94.1,XXXX4,1,0,0,1,0,1, “XXXXX”,现场, “未知”,未知,未知,未知,_ROUTER_HAS_NO_RADIO_, 未知,未知,未知,未知的,2017年1月24日,16时03分43秒,,,,,,, ,,,,

这是我的代码

import csv 
import datetime 
import re 

input_file = 'input22.csv' 
output_file= 'temp.csv' 

def main(): 
    with open(input_file,"r") as fileHandle: 
     CSVreader = fileHandle.readlines() 
     fileHandle.close() 
     reader = CSVreader[-1] 

    with open ('temp.csv',"w") as fileHandle: 
     fileHandle.write(reader) 
     fileHandle.close() 

    with open('temp.csv') as temp_file: 
     readCSV = csv.reader(temp_file, delimiter=',') 
     for row in readCSV: 
      Date=(row[22]) 
      Time=(row[23]) 
      D=Date.strip() 
      T=Time.strip() 
      print ("{} {}".format(D,T)) 


main() 
+0

你可以使用'''pandas''来直接读取csv在一行中并获得任何列。 – TrigonaMinima

+0

你想完成什么? – pnovotnak

回答

0

有些问题我看马上与您的代码蝙蝠 - 没有必要当你把它用with块打开关闭文件。使用上下文的重点在于,只要您离开该块,该文件就会关闭。

例如;

with open ('temp.csv',"w") as fileHandle: 
    fileHandle.write(reader) 
    fileHandle.close() 

应该是;

with open ('temp.csv',"w") as fileHandle: 
    fileHandle.write(reader) 

就是这样! Python为你处理关闭文件。

下,不要使用fh.readlines()。如果文件太大而无法放入内存,则会将整个文件读入内存,并可能导致计算机崩溃。相反,iterate over the file, as per the documentation。在这种情况下,看起来像;

with open(input_file, "r") as fileHandle: 
    CSVreader = csv.reader(fileHandle) 
    for row in CSVreader: 
     # do something with the row 

Python会自动缓冲您的读取,并且只会将文件的一小部分一次保留在内存中。附注:您当前拥有它的样子,你正在阅读的整个文件到CSVreader应该真的只是叫rows或东西,因为这是不是一个reader对象。

最后,在第一个实例中不需要将模式传递给open()调用 - 您可以使用第二次打开temp.csv时使用的语法。

我相信这(未经测试)段完成同样的事情是你的,多了几分简洁和高效。

import csv 
import datetime 
import re 

input_file = 'input22.csv' 
output_file= 'temp.csv' 

def main(): 
    last = list() # scope this variable so that we may use it after the files have been closed 
    with open(input_file) as input_fh, \ 
      open('temp.csv', 'w') as output_fh: 
     reader = csv.reader(input_fh) 
     writer = csv.writer(output_fh) 
     # discard everything except the last line of output 
     for row in reader: 
      last = row 
     writer.write(last) 

    # print that last row with formatting 
    D=last[22].strip() 
    T=last[23].strip() 
    print ("{} {}".format(D,T)) 

main() 
+0

感谢您的代码,您将我主要关心的问题缓存在1个变量中的全部行中。以下代码与writer.writerows(最后)一起工作。 –