def read24list(file):
""" 读取24条已有的数据列表 """
data = []
list24 = []
getIndex24 = []
# 方法2: with优化文件操作
with open (file, "r", encoding="UTF-8") as fileName:
line = fileName.readline ()
line = line[:-1] # 第一行数据内容,(容易误删)
list24.append (line.split ())
while line:
# 按行读取数据
line = fileName.readline ()
line = line[:-1]
list24.append (line.split ()) # 默认按照空格和Tab作为分割
# 删除尾元素
list24.remove (list24[-1])
# 取2维列表的元素,并对每个子列表进行遍历
# for index2 in list24:
# getIndex24.append (index2[1])
# print (getIndex24)
# outlist = list (set (getIndex24))
# print (outlist) # 列表——》集合,元素去重复——》列表
return list24
# 2000条数据列表
def read2000list(file):
""" 读取1200数据,进行筛选和比较 """
data = []
list2000 = []
getIndex2000 = []
getIndex24 = []
# 方法2: with 优化文件操作
with open (file, "r", encoding="UTF-8") as fileName:
line = fileName.readline ()
line = line[ :-1 ] # 第一行数据内容,(容易误删)
list2000.append ( line.split () )
while line:
# 按行读取数据
line = fileName.readline ()
line = line[:-1]
list2000.append (line.split ()) # 默认按照空格和Tab作为分割
# 删除尾元素
list2000.remove (list2000[-1])
# 取2维列表的元素,并对每个子列表进行遍历
list24 = read24list("24ricedetail.txt")
for element24 in list24:
getIndex24.append (element24[1])
for element2000 in list2000:
getIndex2000.append (element2000[1])
# 取2维列表的元素,并对每个子列表进行遍历
if element2000[1] in getIndex24:
# 米种已存在
print("yes,it is in the list",element2000[1])
else:
# 米种不存在
print("this element is out of the list",element2000[1])
str = txtLength("24ricedetail.txt") + '\t' + '\t'.join(element2000) + "\n"
writeDataIntoTxt(str, "24ricedetail.txt")
return list2000
# 在文件的末尾追加数据
def writeDataIntoTxt(object,filename):
with open(filename,"a+",encoding="UTF-8") as fwIn:
fwIn.writelines(object)
# 统计txt文件的总行数
def txtLength(filename):
with open(filename, 'r',encoding="UTF-8") as f:
return str(len(f.readlines()))
if __name__ == "__main__":
print ("----start------")
file2000 = "2000ricedetail.txt"
read2000list (file2000)
print ("----End------")
02-数据操作【读、写、拼接、清洗、函数封装】
最新推荐文章于 2024-05-24 11:35:30 发布
本文介绍了一种从文件中读取数据并进行处理的方法,包括读取24条和2000条数据列表,对比两个列表中的特定元素,以及在文件末尾追加数据。通过Python代码实现,展示了如何使用with语句优化文件操作,以及如何遍历二维列表进行数据筛选和比较。
391

被折叠的 条评论
为什么被折叠?



