python - Python中的CSV文件处理

标签 python file csv

我使用输出到具有以下格式的文本文件的空间数据:

COMPANY NAME
P.O. BOX 999999
ZIP CODE , CITY 
+99 999 9999
23 April 2013 09:27:55

PROJECT: Link Ref
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
Design DTM is 30MB 2.5X2.5
Stripping applied to design is 0.000

Point Number      Easting     Northing        R.L. Design R.L.  Difference  Tol  Name
     3224808   422092.700  6096059.380       2.520     -19.066     -21.586  --   
     3224809   422092.200  6096059.030       2.510     -19.065     -21.575  --   
<Remainder of lines>
 3273093   422698.920  6096372.550       1.240     -20.057     -21.297  --   

Average height difference is -21.390
RMS  is  21.596
0.00 % above tolerance
98.37 % below tolerance
End of Report

如图所示,文件有页眉和页脚。数据由空格分隔,但列之间的数量不相等。

我需要的是以逗号分隔的文件,其中包含东距、北距和差值。

我想避免手动修改数百个大文件,我正在编写一个小脚本来处理这些文件。这是我目前所拥有的:

#! /usr/bin/env python
import csv,glob,os
from itertools import islice
list_of_files = glob.glob('C:/test/*.txt')
for filename in list_of_files:
(short_filename, extension )= os.path.splitext(filename)
print short_filename
file_out_name = short_filename + '_ed' + extension
with open (filename, 'rb') as source:
    reader = csv.reader( source) 
    for row in islice(reader, 10, None):
        file_out= open (file_out_name, 'wb')
        writer= csv.writer(file_out)
        writer.writerows(reader)
        print 'Created file: '+ file_out_name
        file_out.close()
print 'All done!' 

问题:

  • 如何让以“Point number”开头的行成为输出文件中的标题?我正在尝试用 DictReader 代替读写器位,但无法正常工作。

  • 用分隔符“,”写入输出文件确实有效,但在每个空格处写了一个逗号,让我的输出文件中有太多空列。我该如何避免这种情况?

  • 如何删除页脚?

最佳答案

我发现你的代码有问题,你正在为每一行创建一个新的 writer;所以你最终只会得到最后一个。

您的代码可能是这样的,不需要 CSV 读取器或写入器,因为它足够简单,可以被解析为简单文本(如果您有文本列、转义字符等,就会出现问题)。

def process_file(source, dest):
  found_header = False
  for line in source:
    line = line.strip()
    if not header_found:
      #ignore everything until we find this text
      header_found = line.starswith('Point Number')
    elif not line:
      return #we are done when we find an empty line, I guess
    else:
      #write the needed columns
      columns = line.split()
      dest.writeline(','.join(columns[i] for i in (1, 2, 5)))

for filename in list_of_files:
  short_filename, extension = os.path.splitext(filename)
  file_out_name = short_filename + '_ed' + extension
  with open(filename, 'r') as source:
    with open(file_out_name. 'w') as dest:
      process_file(source, dest)

关于python - Python中的CSV文件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16275498/

相关文章:

python - 将 pandas 数据框索引 reshape 为列

python - 如何在 Python 中生成 TCP、IP 和 UDP 数据包

.net - 使用 .NET 创建 TrueType 字体文件的子集

java - 在 JFileChooser 上使用 JComboBox 列出以组合框第一行文本开头的所有文件

Python打开动态变化的文件路径

c - 检索 csv 文件的列 ID

Python 并没有明显的方法从字典中获取特定元素

python - 没有名为 psycopg2 的模块

php - 有没有办法通过网页上的链接打开用户计算机上本地网络上的文件?

python - 从 cpp、python 和 csv 文件中生成可执行文件?