我正在尝试将文本文件的行读入 python 中的列表或数组。我只需要能够在创建列表或数组后单独访问其中的任何项目。
该文本文件的格式如下:
0,0,200,0,53,1,0,255,...,0.
如上所述...,实际的文本文件有数百或数千个项目。
...
我正在使用以下代码尝试将文件读入列表:
text_file = open("filename.dat", "r") lines = text_file.readlines() print lines print len(lines) text_file.close()
我得到的输出是:
['0,0,200,0,53,1,0,255,...,0.'] 1
显然,它将整个文件读入一个仅包含一个项目的列表,而不是单个项目的列表。我做错了什么?
您遇到的问题是,由于readlines()拆分,文件的整个内容被读取为单个字符串\n),
readlines()
\n
您可以按照以下方法修改代码来实现此目的:
# Open the file and read the content with open("filename.dat", "r") as text_file: # Read the entire file content as a string and strip any extra whitespace or newlines content = text_file.read().strip() content = text_file.read().strip content = text_file.read(). content = text_file.read content = text content = # Split the string by commas to get individual items data_list = content.split(',') # Optional: Convert the items to integers (since they appear to be numbers) data_list = [int(item) for item in data_list] # Now you can access individual items in the list print(data_list) # To see the full list print(len(data_list)) # Number of items in the list print(data_list[0]) # Access the first item print(data_list[-1]) # Access the last item
with open(..., "r")
text_file.read().strip()
split(',')
[int(item) for item in data_list]
如果您的文件包含:
0,0,200,0,53,1,0,255,...,0
输出data_list将如下所示:
data_list
[0, 0, 200, 0, 53, 1, 0, 255, ..., 0]
现在您可以data_list通过索引访问单个项目,并len(data_list)给出正确的项目数量。
len(data_list)