我是编程新手,我的一项作业需要帮助。 (不要求解决方案)。我很困惑如何解决这个问题。如果您能提供伪代码让我朝着正确的方向前进,那将很有帮助。
到目前为止,
- 接受一个文件的输入
- 读取文件 testFile = inputFile.read()
- 这就是我感到困惑的地方。我知道需要有一个 for 循环来遍历文本文件。计算 testFile 中行的总和://Logic
引用Text File用于文本文件和相应的预期输出。
例如:不使用镜头功能
x = input("输入要读取的文件:") y = input("输入要写入的文件:")
filereading = x.readline()
我需要删除哪些字符才能添加两个值。此外,我需要输出中包含 $#,中间有一个空格。
对于文件读取中的行: \逻辑
请您参考如下方法:
伪代码
open file as test_file
read test_file into something
split something to make list out of something
loop through something
remove $ from all items in something
open other_file to write to
create loop to sum 2 consecutive items in something
create variable to hold total of two items
write output statement to other_file
试着用文字写出我是如何处理它的想法来帮助指导你,下面是答案,同样不是为了让你跳到,而是在你遇到困难时用作指导。
...
...
...
...
剧透:解决方案
test_file = open('money.txt', 'r')
content = test_file.read()
content = content.split()
for i in range(len(content)):
content[i] = content[i].strip('$')
other_file = open('print.txt', 'w')
for i in range(0, len(content), 2):
total = float(content[i]) + float(content[i+1])
other_file.write(f"${content[i]} + ${content[i+1]} = ${total}\n")
test_file.close()
other_file.close()
额外的
with open(other_file, 'w') as f_obj:
total = float(content[0]) + float(content[1])
f_obj.write("$ " + content[0] + " $ " + content[1] + " $ " +
str(total) + "\n")
total = float(content[2]) + float(content[3])
f_obj.write("$ " + content[2] + " $ " + content[3] + " $ " +
str(total) + "\n")
total = float(content[4]) + float(content[5])
f_obj.write("$ " + content[4] + " $ " + content[5] + " $ " +
str(total) + "\n")
这是一个关于如何手动输入每个语句的例子,还要注意如果你像这个例子一样使用with open,文件应该在之后 代码完成close with open
