我从 txt 文件中读取元素,我想将元素写入数组,我知道我必须使用 substring 方法,但我不知道如何在使用 substring 方法时生成数组。
example.txt 文件包括
001, A, 50, 70, 65
002, B, 25, 55, 80
003, C, 60, 40, 85
004, D, 75, 55, 70
005, E, 40, 40, 45
006, F, 35, 25, 85
我的python代码:
file = open("example.txt", "r")
a = file.read()
print(a)
我需要生成 30 个元素的多维(5x6)数组,我可以使用此代码读取此文件的元素,但我想知道如何将它们写入数组。
要获得多维数组,您需要逐行读取文件,并用逗号分割每一行,就像我之前的回答一样
# Prepare result array:
array = []
# Open file
with open("example.txt", "r") as f:
# read the contents of file line by line:
for line in f:
# split current line by comma to get array of items from it
array_parts = line.split(",")
# filter elements, removing empty, and stripping spaces:
array_parts = [item.strip() for item in array_parts if item.strip() != ""]
# add line's items into result array:
array.append(array_parts)
# Printing result:
print(array)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句