gpt4 book ai didi

python - 在 Python 中从制表符分隔的文件中读取并导出单列

转载 作者:行者123 更新时间:2023-12-01 04:25:20 25 4
gpt4 key购买 nike

我有许多大型制表符分隔文件,另存为 .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 的解决方案> 或其他内置模块!

最佳答案

您必须一次处理一行文件:读取、解析和写入。

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:
with open(output_file, "wb") as tmp_file:
reader = csv.reader(to_read, delimiter = "\t")
writer = csv.writer(tmp_file)

desired_column = [6] # text column

for row in reader: # read one row at a time
myColumn = list(row[i] for i in desired_column) # build the output row (process)
writer.writerow(myColumn) # write it

关于python - 在 Python 中从制表符分隔的文件中读取并导出单列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33217277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com