Skip to main content
 首页 » 编程设计

python之在 python 中写入空列

2025年05月04日13shanyou

我有以下两种类型的txt文件:

文件1

Sample1012, Male, 36, Stinky, Bad Hair 
Sample1043, Female, 28, Hot, Short Hair, Hot Body, Hates Me 
Sample23905, Female, 42, Cougar, Long Hair, Chub 
Sample123, Male, 32, Party Guy 

文件2

DEAD, Sample123, Car Accident, Drunk, Dumb 
ALIVE, Sample1012, Alone 
ALIVE, Sample23905, STD 
DEAD, Sample1043, Too Hot, Exploded 

我只想编写一个简单的 Python 脚本来根据样本字段连接这些文件,但一直遇到数据列随机数的问题。例如,我最终得到:

Sample1012, Male, 36, Stinky, Bad Hair, ALIVE, Sample1012, Alone 
Sample1043, Female, 28, Hot, Short Hair, Hot Body, Hates Me, DEAD, Sample1043, Too Hot, Exploded 
Sample23905, Female, 42, Cougar, Long Hair, Chub, ALIVE, Sample23905, STD 
Sample123, Male, 32, Party Guy, DEAD, Sample123, Car Accident, Drunk, Dumb 

当我想要的是:

Sample1012, Male, 36, Stinky, Bad Hair, EMPTY COLUMN, EMPTY COLUMN, ALIVE, Sample1012, Alone 
Sample1043, Female, 28, Hot, Short Hair, Hot Body, Hates Me, DEAD, Sample1043, Too Hot, Exploded 
Sample23905, Female, 42, Cougar, Long Hair, Chub, EMPTY COLUMN, ALIVE, Sample23905, STD 
Sample123, Male, 32, Party Guy, EMPTY COLUMN, EMPTY COLUMN, EMPTY COLUMN, DEAD, Sample123, Car Accident, Drunk, Dumb 

我基本上只是用 .readlines() 读取两个文件,然后用简单的“==”将相关列与样本 ID 进行比较,如果为真,则打印出第一个文件中的行和第二。

不确定如何使用 len() 来确定 file1 中的最大列数,这样我就可以在每行末尾说明这一点,如果它不是最大列数,然后再从另一个文件追加该行(前提是“==”为真)。

非常感谢任何帮助。

更新:

这是我现在得到的:

import sys 
import csv 
 
usage = "usage: python Integrator.py <table_file> <project_file> <outfile>" 
if len(sys.argv) != 4: 
    print usage 
    sys.exit(0) 
 
project = open(sys.argv[1], "rb") 
table = open(sys.argv[2], "rb").readlines() 
outfile = open(sys.argv[3], "w") 
 
table[0] = "Total Table Output \n" 
 
newtablefile = open(sys.argv[2], "w") 
for line in table: 
    newtablefile.write(line) 
 
projectfile = csv.reader(project, delimiter="\t") 
newtablefile = csv.reader(table, delimiter="\t") 
 
result = [] 
 
for p in projectfile: 
    print p 
    for t in newtablefile: 
        #print t 
        if p[1].strip() == t[0].strip(): 
            del t[0] 
            load = p + t 
            result.append(load) 
 
 
for line in result: 
    outfile.write(line) 
 
outfile.close() 

无法让 for 循环一起工作 - 不要介意停止时的愚蠢内容。其中一个文件的第一行是空白。

请您参考如下方法:

不确定在您建议的输出中“空列”来自何处...如果这些列应该与定义的模式相匹配,那么您必须在输入文件中有空白点。否则,这将起作用...

import csv 
 
 
f1 = open("test1.txt", 'rb') 
reader1 = csv.reader(f1) 
f2 = open("test2.txt", 'rb') 
reader2 = csv.reader(f2) 
result = [] 
 
for entry in reader1: 
    print entry 
    for row in reader2: 
        print row 
        if entry[0].strip() == row[1].strip(): 
            del row[1] 
            load = entry + row 
            result.append(load) 
 
for line in result: 
    print line 

编辑 -

如果您需要跳过其中一个文件中的一行,您可以这样做 reader1.next() 它将指针移动到输入的下一行。

你的例子你创建了一个输出文件,你向它写入数据,然后尝试读取它而不关闭文件并重新打开它,或者以可读和可写的方式打开它......我不能发誓,但我认为这可能是你的问题。幸运的是,您不需要使用 .next() 方法执行所有这些操作。