问题
如何编写将在输出中插入插入符号行的代码,其中输入中有一个?
代码
data1=[]
with open("FileInput1.txt") as file:
for line in file:
data1.append([float(f) for f in line.strip().split()])
data2=[]
with open("FileInput2.csv") as File2:
for line in File2:
data2.append([f for f in line.strip().split()])
示例输入:
文件输入#1
1223 32 (userID - int = 1223, work hours = 32)
2004 12.2
8955 80
一个。电流输出
1223 32 2004 12.2 8955 80
FileInput2:
UserName 3423 23.6
Name 6743 45.9
一个。电流输出
UserName 3423 23.6 Name 6743 45.9
答案 0 :(得分:2)
<强>排除强>
基于上帝的神秘信息(请不被冒犯),我已经破译了Amina's个问题。这是导致这一切的对话:
So... this is a programming exercise in which the output is exactly
the same as the input?
– xxmbabanexx 12 mins ago
@xxmbabanexx - lol yes – Amina 8 mins ago
<强>答案强>
要在输出中保留换行符,只需打印完全文件即可。如果我没有进行上述对话,我会给出一个更复杂的答案。这是一步一步给出的答案。
"""
Task: Make a program which returns the exact same output as the input
Ideas:
print the output!!
"""
^这有助于我理解问题
first_input = "Input_One.txt"
second_input = "Input_Two.txt"
Input_One = open(first_input, "r")
Input_Two = open (first_input, "r")
Output_One = open("Output_One.txt", "w")
Output_Two = open ("Output_Two.txt", "w")
^我创建并打开我的两个文件。
x = Input_One.read()
y = Input_Two.read()
^我读取了信息,为其分配了变量x
和y
print "OUTPUT 1:\n", x
print "\n"
print "OUTPUT 2:\n", y
^我向用户显示输出
#Save "output"
Output_One.write(x)
Output_Two.write(y)
print"\nCOMPLETE!"
^我保存输出并发送消息。
答案 1 :(得分:1)
您正在做的只是将文件中的多行合并为一行。
def printer(filename, data):
with open(filename, "w") as f:
f.write(data.replace("\n", " "))
for filename in ["FileInput1.txt", "FileInput2.csv"]:
with open(filename) as f:
printer("new" + filename, f.read())