我想从sys.stdin中读取两个不同的文件,我可以读写文件但是没有与第一个和第二个文件分开。
当我在cmd win 10和python 3.6上运行以下代码时:
-H "Content-Type: application/json"
结果是:
1 2 3 4 5 1 2 3 4 5 6 7
我可以打印这两个文件。
我的python代码是:
D:\digit>cat s.csv s2.csv
我在cmd提示符下运行命令:
import sys
import numpy as np
train=[]
test=[]
#Assume below code is function 1 which just and must read s.csv
reader = sys.stdin.readlines()
for row in reader:
train.append(int(row[0]))
train = np.array(train)
print(train)
#I need some thing here to make separation
#sys.stdin.close()
#sys.stdin = sys.__stdin__
#sys.stdout.flush()
#Assume below code is function 2 which just and must read s2.csv
reader = sys.stdin.readlines()
for row in reader:
test.append(int(row[0]))
test = np.array(test)
print(test)
结果是:
D:\digit>cat s.csv s2.csv | python pytest.py
我是否需要为下一个文件重置sys.stdin? 我使用下面的,但没有一个回答:
[1 2 3 4 5 1 2 3 4 5 6 7]
[]
感谢您提前获取任何帮助。
答案 0 :(得分:2)
另一种解决方案是:
import sys
train=[]
args = sys.stdin.readlines()[0].replace("\"", "").split()
for arg in args:
arg=arg.strip()
with open(arg, "r") as f:
train=[]
for line in f:
train.append(int(line))
print(train)
s.txt是:
1
2
3
s2.txt是:
7
8
9
D:\digit>echo s.txt s2.txt | python argpy.py
[1, 2, 3]
[7, 8, 9]
关键是两点:
使用echo而不是cat来防止连接 要学习更多内容的链接:Difference between 'cat < file.txt' and 'echo < file.txt'
尝试通过拆分每个文件并存储在args中来读取每个新文件的for循环。 How to run code with sys.stdin as input on multiple text files
快乐bc我已经完成了它:)