Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中合并两个没有公共列的文本文件_Python_File_Join - Fatal编程技术网

在python中合并两个没有公共列的文本文件

在python中合并两个没有公共列的文本文件,python,file,join,Python,File,Join,我有两个行数相同的文本文件,但文件之间没有公共列。第一个文件有9列,第二个文件有8列。它们都有111557行。两个文件中的行顺序相同,所以我只想简单地合并它们,这意味着我将有一个包含17列的文本文件 这是第1个.txt文件的第一列(它们受制表符限制) 这是第2.txt文件的第1行(它们受制表符限制) 试着这样做: with open('file1') as f1, open('file2') as f2, open('outfile','w') as out: for x in f1:

我有两个行数相同的文本文件,但文件之间没有公共列。第一个文件有9列,第二个文件有8列。它们都有111557行。两个文件中的行顺序相同,所以我只想简单地合并它们,这意味着我将有一个包含17列的文本文件

这是第1个.txt文件的第一列(它们受制表符限制)

这是第2.txt文件的第1行(它们受制表符限制)

试着这样做:

with open('file1') as f1, open('file2') as f2, open('outfile','w') as out:
    for x in f1:
        y = next(f2)
        out.write("{}\t{}".format(x.strip(),y))
如果上面出现错误,请尝试以下操作:

f1 = open('file1') 
f2 = open('file2')
out = open('outfile','w')
for x in f1:
    y = next(f2)
    out.write(x.strip() + "\t" + y)

请从每个文件中发布一行,并在输出文件中发布相应的所需行。列之间用什么隔开?好的,这太多了。你试过用谷歌搜索什么吗?你有自己的代码吗?哪怕是一行打开一个文件?要从文件中读取行吗?将一行写入文件?我有一种感觉,OP@ali:这就是为什么我在你原来的帖子上发表评论要求澄清的原因。请解决这个问题,没有它我无法提供一个超级准确的答案answer@ali:我已经更新了我的答案,使之完全符合您的需要。我喜欢它,但这只适用于OP的文件以空格分隔的情况,这与我的假设类似。问题真的不是很清楚@Hackaholic my files are tab Limited引发了以下错误:语法错误:无效语法,它与以下内容相关:“,”在f1之后,open('firsts.txt')作为f1,open('eights.txt')作为f2,open('outfile.txt','w')作为out:^SyntaxError:invalidsyntax@ali检查解决方案的下一个版本
import csv

with open('path/to/file1') as infile1, open('path/to/file2') as infile2, open('path/to/output', 'w') as outfile:
    writer = csv.writer(outfile, delimiter='\t')
    for row1,row2 in zip(csv.reader(infile1, delimiter='\t'), csv.reader(infile2, delimiter='\t')):
        writer.writerow(row1+row2)
with open('file1') as f1, open('file2') as f2, open('outfile','w') as out:
    for x in f1:
        y = next(f2)
        out.write("{}\t{}".format(x.strip(),y))
f1 = open('file1') 
f2 = open('file2')
out = open('outfile','w')
for x in f1:
    y = next(f2)
    out.write(x.strip() + "\t" + y)