我正在编写一个程序,该程序从文本文件中读取和提取数据,然后对数据进行一些计算。
但是,由于我的文本文件中有空格,检索数字时出现错误。我得到
ValueError:int() 的无效文字与 base10: ' '
我的文本文件看起来像这样:
['flower', 'sdfsd', '21/08/2019 20:27:03', 1]
['hello', 'sdsdfsdf', '21/08/2019 20:27:36', '2']
['car', 'sdfsd', '21/08/2019 20:27:45', 1]
['table', 'sdfsdf', '21/08/2019 20:29:21', 1]
_(blank space \n)_
['shirt', 'sdfsdf', '21/08/2019 20:30:02', '2']
_(blank space \n)_
['hello', 'sdfsdf', '21/08/2019 20:30:07', '3']
我从 python 写入文本文件的代码如下所示:
historyFile = open('history.txt','a')
historyFile.write("\n\r")
historyFile.write(file)
historyFile.close()
我已经尝试过在线示例,if not line.strip():
但它在空行后停止检索数据
以下是我的代码:
readFile = open('history.txt','r')
searching = readFile.readlines()
i=0
for line in searching:
if i in range(len(searching)-1):
i += 1
oldCount = str(int(searching[i].split(",")[3][-4]))
newCount = str(int(searching[i].split(",")[3][-4]) + 1)
print("\nold count: " + oldCount + " new count: " + newCount)
它应该遍历我的文本文件中的所有行并返回我列表中位置 3 的数字,但由于空行,我收到错误
如果您history.txt
包含(注意空行):
flower, 'sdfsd', '21/08/2019 20:27:03', 1
hello, 'sdsdfsdf', '21/08/2019 20:27:36', 2
car, 'sdfsd', '21/08/2019 20:27:45', 1
table, 'sdfsdf', '21/08/2019 20:29:21', 1
shirt, 'sdfsdf', '21/08/2019 20:30:02', 2
hello, 'sdfsdf', '21/08/2019 20:30:07', 3
然后这个脚本将读取文件并打印增加 1 的最后一列:
with open('history.txt', 'r') as readFile:
for i, line in enumerate(readFile, 1):
line = line.strip()
if not line:
continue
line_tuple = tuple(map(str.strip, line.split(',')))
oldCount = int(line_tuple[3])
newCount = oldCount + 1
print("row no. {} old count: {} new count: {}".format(i, oldCount, newCount))
印刷:
row no. 1 old count: 1 new count: 2
row no. 2 old count: 2 new count: 3
row no. 3 old count: 1 new count: 2
row no. 4 old count: 1 new count: 2
row no. 6 old count: 2 new count: 3
row no. 8 old count: 3 new count: 4
编辑:如果您history.txt
包含引用的字段:
'flower','sdfsd','21/08/2019 20:27:03','1'
'hello','sdsdfsdf','21/08/2019 20:27:36','2'
'car','sdfsd','21/08/2019 20:27:45','1'
'table','sdfsdf','21/08/2019 20:29:21','1'
'shirt','sdfsdf','21/08/2019 20:30:02','2'
'hello','sdfsdf','21/08/2019 20:30:07','3'
您可以使用csv
模块来读取它:
import csv
with open('history.txt', 'r') as readFile:
csvreader = csv.reader(readFile, delimiter=',', quotechar="'")
for i, line in enumerate(csvreader, 1):
if not line:
continue
oldCount = int(line[3])
newCount = oldCount + 1
print("row no. {} old count: {} new count: {}".format(i, oldCount, newCount))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句