Python 通过stdin input()读取文件时,它';只有一行

Python 通过stdin input()读取文件时,它';只有一行,python,python-3.x,file,stdin,Python,Python 3.x,File,Stdin,在cmd中运行此代码时,通过命令:py file.py textfile.txt, 出于某种原因,它只读取textfile.txt的第一行,我不明白为什么 input_numbers = [] final_numbers_array = [] input_file = input() print (input_file) input_numbers = input_file.split(" ") for x in range(len(input_numbers)):

在cmd中运行此代码时,通过命令:
py file.py textfile.txt
, 出于某种原因,它只读取textfile.txt的第一行,我不明白为什么

input_numbers = []
final_numbers_array = []

input_file = input()
print (input_file)
input_numbers = input_file.split(" ")

for x in range(len(input_numbers)):
    if(input_numbers[x]!=""):
        final_numbers_array.append(int(input_numbers[x]))

    elif(input_numbers[x]!="\n"):
         final_numbers_array.append(int(input_numbers[x]))

    elif(input_numbers[x]!="\t"):
         final_numbers_array.append(int(input_numbers[x]))

    else:
        pass
            
print(final_numbers_array)
试试这个:

import re
import sys

if __name__ == '__main__':

    num_array = []

    with open(sys.argv[1], 'r') as num_file:
        for line in num_file:
            num_array.extend(re.findall('\d+', line))

    print(num_array)
这将读取文本文件的每一行,并为您提供一个数字数组。 如果需要整数数组而不是字符串,请使用此行将其转换为:

num_array = [int(num) for num in num_array]

您正在处理文件名,而不是文件内容。它实际上读取第一行,所以我不这么认为,它读取第一行并打印它,但没有其他内容。但是您的代码中没有
open
,它如何读取文件?我是一名编程人员,但有人告诉我,通过输入它,它以字符串的形式输入文件和文件内容,当你这样写的时候调用它。不,你所描述的与工作方式根本不匹配。您有许多基本的误解,需要遵循教程,而不是试图获得有关堆栈溢出的帮助。这超出了这里单个问题的范围,可以提出的单个问题以前都被反复提出过(现有教程和文档也涵盖了这些问题)。