如何用Python 3从命令行读取任意数量文本文件并逐行拼接?
Solution for Line-by-Line Concatenation of Multiple Text Files in Python 3
Got it, let's break down how to solve this problem. The goal is to take any number of text files passed via the command line, pair up their corresponding lines, concatenate each group of lines into a single string, then combine all those results into one final output.
Step-by-Step Approach
- Read command-line arguments: Grab all the file paths provided when running the script (skip the script name itself).
- Load lines from each file: Open each file, read its lines, and strip off trailing newline characters to avoid extra spaces in the output.
- Pair corresponding lines: Use Python's built-in
zip()function to line up lines from each file—this stops at the shortest file if lengths differ, which matches your example where all files have the same line count. - Concatenate and combine: For each group of paired lines, join them with spaces, then join all those groups into the final output string.
Complete Code Example
import sys def concatenate_files(): # Get file paths from command line (skip script name) file_paths = sys.argv[1:] if not file_paths: print("Error: Please provide at least one text file path.") return # Read lines from each file, stripping newline characters try: file_lines = [] for path in file_paths: with open(path, 'r') as f: # Preserve internal whitespace, only strip trailing newlines lines = [line.rstrip('\n') for line in f] file_lines.append(lines) except FileNotFoundError as e: print(f"Error: Could not find file '{e.filename}'") return # Pair lines across files and concatenate each group concatenated_parts = [] for line_group in zip(*file_lines): concatenated_parts.append(' '.join(line_group)) # Combine all parts into the final output final_output = ' '.join(concatenated_parts) print(final_output) if __name__ == "__main__": concatenate_files()
How to Test This
Let's use your example files:
pizza.txt:Margarita Pepperoni Mushroompasta.txt:Spaghetti Carbonara Lasagnadrinks.txt:Beer Wine Soda
Run the script with these files:
python3 concat_files.py pizza.txt pasta.txt drinks.txt
You'll get the expected output:
Margarita Spaghetti Beer Pepperoni Carbonara Wine Mushroom Lasagna Soda
Handling Files with Different Line Counts
If your files have uneven line lengths, zip() will stop at the shortest file. To include all lines (filling empty strings for missing lines in shorter files), use itertools.zip_longest:
from itertools import zip_longest # ... (keep the rest of the code the same) for line_group in zip_longest(*file_lines, fillvalue=''): concatenated_parts.append(' '.join(line_group))
You can change fillvalue to something like 'N/A' if you want a placeholder instead of empty strings.
内容的提问来源于stack exchange,提问作者Kid Convalescent
相关产品推荐
相关产品推荐

