You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python将1.csv与2.txt合并为指定格式的3.csv?

Fixing Row-wise File Merging in Python

Got it, let's sort out why your current code isn't working and fix this properly. The problem with using fileinput here is that it iterates through all lines of the first file first, then all lines of the second file—so you end up with all 1.csv lines followed by all 2.txt lines, not the paired rows you need.

To merge corresponding lines from the two files, we need to read them in parallel, pairing each line from 1.csv with the matching line from 2.txt. Here's how to do it right:

Basic Solution (for matching line counts)

This works perfectly for your 2-line example (and any case where both files have exactly the same number of lines):

# Use with statements to safely handle file opening/closing
with open('1.csv', 'r') as csv_file, open('2.txt', 'r') as txt_file, open('3.csv', 'w') as output_file:
    # Zip the two file iterators to pair lines row-by-row
    for csv_line, txt_line in zip(csv_file, txt_file):
        # Strip newline characters from each line to avoid messy gaps
        cleaned_csv = csv_line.strip()
        cleaned_txt = txt_line.strip()
        # Combine the lines with a comma and add a newline for the output
        combined_row = f"{cleaned_csv},{cleaned_txt}\n"
        output_file.write(combined_row)

Breakdown of how this works:

  • with statements ensure all files are closed automatically after processing, even if an error pops up.
  • zip(csv_file, txt_file) pulls one line from each file at a time, so line 1 of 1.csv pairs with line 1 of 2.txt, line 2 pairs with line 2, etc.
  • strip() removes trailing newlines (and any extra whitespace) so we don't get weird line breaks in the final 3.csv.

Handling Unequal Line Counts

If you might end up with files that have different numbers of lines later, use itertools.zip_longest to keep processing until the longest file is exhausted. Missing lines will be filled with empty strings:

from itertools import zip_longest

with open('1.csv', 'r') as csv_file, open('2.txt', 'r') as txt_file, open('3.csv', 'w') as output_file:
    # zip_longest continues until the longest file is done, using fillvalue for missing lines
    for csv_line, txt_line in zip_longest(csv_file, txt_file, fillvalue=''):
        # Handle cases where one line might be None (if a file is shorter)
        cleaned_csv = csv_line.strip() if csv_line else ''
        cleaned_txt = txt_line.strip() if txt_line else ''
        combined_row = f"{cleaned_csv},{cleaned_txt}\n"
        output_file.write(combined_row)

Run either script, and you'll get exactly the 3.csv output you want:

traider1,domain.net,tomb,Raider1,TECH-1377
traider,domain.net,tomb,Raider,TECH-1366

内容的提问来源于stack exchange,提问作者Milister

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:34:05