Python如何从外部文件读取输入?
Great question! When you're testing Python programs for time and space complexity with large datasets, manually typing input is not just tedious—it's a huge waste of time that could be spent analyzing your algorithm's performance. Let's walk through a few practical ways to feed input from a TXT file into your program:
方法1:直接读取文件内容(适合愿意修改程序代码的场景)
If your program was originally written to take input via input() or sys.stdin, you can easily replace that with direct file reading. This gives you full control over how you parse the input data.
Example 1: Reading line-by-line
Suppose your program expects the first line to be the number of elements, followed by each element on its own line:
# 原来的手动输入版本 n = int(input()) nums = [int(input()) for _ in range(n)] # 修改为从文件读取 with open('input_data.txt', 'r') as f: # 读取第一行作为元素数量 n = int(f.readline().strip()) # 读取后续n行,转换为整数列表 nums = [int(f.readline().strip()) for _ in range(n)] # 继续运行你的算法逻辑 print(sum(nums)) # 示例操作
Example 2: Reading all data at once
If your input is formatted as a single line of space-separated values, or you want to process all data in one go:
with open('input_data.txt', 'r') as f: # 读取所有内容,按空白字符拆分(包括换行和空格) raw_data = f.read().split() # 转换为整数列表(根据你的需求调整类型) input_data = list(map(int, raw_data)) # 用input_data执行你的算法
方法2:命令行输入重定向(无需修改现有代码)
This is my go-to trick when I don't want to touch the existing code that uses input() or sys.stdin. You can redirect the contents of your TXT file to be the standard input for your program directly from the command line.
How to do it:
Run your Python program with this command:
python your_program.py < input_data.txt
That's it! Your program will read input from input_data.txt exactly as if you were typing it manually.
方法3:通过命令行参数指定输入文件(灵活适配多个测试用例)
For more flexibility—like switching between different test files without editing code—use the argparse module to let users pass the input file path as a command-line argument.
Example code:
import argparse # 设置命令行参数解析器 parser = argparse.ArgumentParser(description='Run algorithm with input from a text file.') parser.add_argument('input_file', help='Path to your input TXT file (e.g., ./test_data.txt)') args = parser.parse_args() # 读取指定文件的内容 with open(args.input_file, 'r') as f: data = f.read().split() input_list = list(map(int, data)) # 执行你的算法 print(f"Processed {len(input_list)} elements")
Run it like this:
python your_program.py test_case_1.txt # 或者换另一个测试文件 python your_program.py large_test_case.txt
额外小贴士:快速生成大量测试数据
If you don't already have a large input file, you can write a tiny Python script to generate one for you. For example, here's how to create a file with 100,000 random integers:
import random with open('large_input.txt', 'w') as f: # 先写入元素数量 f.write('100000\n') # 写入100000个随机整数,每行一个 for _ in range(100000): f.write(f"{random.randint(1, 1000)}\n")
Just make sure your input file's format matches what your program expects—if your program is looking for space-separated values instead of lines, adjust the generator script accordingly.
内容的提问来源于stack exchange,提问作者Abhishek Kumar

