gpt4 book ai didi

python - 从列表中写入数据

转载 作者:太空宇宙 更新时间:2023-11-03 21:44:26 24 4
gpt4 key购买 nike

我正在学习 Python,并且需要完成一个练习:

Write a program which will read in lines from a file and select the first three fields (separated by blank space). The program should write a file called error which contains lines which look like Line 362 did not have 3 fields, to identify those which did not have 3 fields. The program should then write, into a file called output, the first three fields in the form of a string of width 10, followed by two floats of width 10 each with 3 places after the decimal point. In case this is not possible, the fields should be written as strings of width 10.

我已经完成了一半,但是我无法将列表项放入错误异常报告中。我没有收到任何错误消息;我只得到一个空文件。

我的异常数据在 Python 中显示,但写入输出丢失。

这是我的代码:

file = open("question3.txt",'r')
read = file.read()
file.close()
print(read)
#This is the list of sentences that form the list 'read'
#I need to analyse these list items.

array = read.splitlines()
print(array)
for item in array:
if(item.count(" "))<3:
exception = str(item)
f = open('error.txt','w')
f.write(exception)
print(exception)
f.close()

我该如何解决这个问题?我不需要问题的完整答案,只需提供有关如何将我已识别到文本文件中的“短列表字段”的建议。

谢谢!

最佳答案

你可以使用

for idx, item in enumerate(array):

跟踪行号,并编写更具信息性的错误消息。

关于python - 从列表中写入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52598832/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com