【发布时间】:2016-01-17 23:15:21
【问题描述】:
我有许多以制表符分隔的大文件保存为.txt,每个文件有七列,标题如下:
#column_titles = ["col1", "col2", "col3", "col4", "col5", "col6", "text"]
我想简单地提取名为text 的最后一列并将其保存到一个新文件中,每一行都是原始文件中的一行,而都是字符串。
编辑:这不是 a similar problem 的副本,因为在我的情况下 splitlines() 不是必需的。只有事情的顺序需要改进
基于 -several - other - posts,这是我目前的尝试:
import csv
# File names: to read in from and read out to
input_file = "tester_2014-10-30_til_2014-08-01.txt"
output_file = input_file + "-SA_input.txt"
## ==================== ##
## Using module 'csv' ##
## ==================== ##
with open(input_file) as to_read:
reader = csv.reader(to_read, delimiter = "\t")
desired_column = [6] # text column
for row in reader:
myColumn = list(row[i] for i in desired_column)
with open(output_file, "wb") as tmp_file:
writer = csv.writer(tmp_file)
for row in myColumn:
writer.writerow(row)
我得到的只是输入文件中第 2624 行的文本字段,该字符串中的每个字母都被分离出来:
H,o,w, ,t,h,e, ,t.e.a.m, ,d,i,d, ,T,h,u,r,s,d,a,y, ,-, ,s,e,e , ,h,e,r,e
我对编程世界知之甚少是随机的,但这绝对是奇怪的!
This post 与我的需求非常相似,但缺少写入和保存部分,我也不确定。
我已经研究过使用 pandas 工具箱(根据上述链接之一),但我无法安装 Python,因此请仅使用 csv 或其他内置模块的解决方案!
【问题讨论】: