[英]How to make a text file into a list of arrays (array-in-array) and remove spaces/newlines
例如我有一個txt文件:
3 2 7 4
1 8 9 3
6 5 4 1
1 0 8 7
每行有4個數字,有4行。 在行尾有 \\n (最后一個除外)。 我的代碼是:
f = input("Insert file name: ")
file = open(f, encoding="UTF-8")
我想要的是文本文件變成[[3,2,7,4],[1,8,9,3],[6,5,4,1],[1,0,8,7]]
.
我什么都試過了,我知道答案可能很簡單,但經過一個小時的嘗試,我真的放棄了。 嘗試了read()
、 readlines()
、 split()
、 splitlines()
、 strip()
以及我可以在互聯網上找到的任何其他內容。 這么多人甚至無法區分它們......
打開文件后,使用你提到的split
和嵌套列表理解來使用這個單行:
with open(f, encoding="UTF-8") as file: # safer way to open the file (and close it automatically on block exit)
result = [[int(x) for x in l.split()] for l in file]
請注意,如果文件中沒有整數,它將失敗。
(作為旁注, file
是python 2中的內置file
,但在python 3中不再存在,但是我通常不使用它)
你可以這樣做,
[map(int,i.split()) for i in filter(None,open('abc.txt').read().split('\n'))]
逐行執行以獲取更多信息
In [75]: print open('abc.txt').read()
3 2 7 4
1 8 9 3
6 5 4 1
1 0 8 7
用換行符split
。
In [76]: print open('abc.txt').read().split('\n')
['3 2 7 4', '', '1 8 9 3', '', '6 5 4 1', '', '1 0 8 7', '']
刪除不必要的空字符串。
In [77]: print filter(None,open('abc.txt').read().split('\n'))
['3 2 7 4', '1 8 9 3', '6 5 4 1', '1 0 8 7']
用空格split
In [78]: print [i.split() for i in filter(None,open('abc.txt').read().split('\n'))]
[['3', '2', '7', '4'], ['1', '8', '9', '3'], ['6', '5', '4', '1'], ['1', '0', '8', '7']]
將元素轉換為int
In [79]: print [map(int,i.split()) for i in filter(None,open('abc.txt').read().split('\n'))]
[[3, 2, 7, 4], [1, 8, 9, 3], [6, 5, 4, 1], [1, 0, 8, 7]]
以下使用列表理解來創建列表列表。 它從文件中讀取每一行,使用空格作為分隔符將其拆分,使用map
函數創建一個迭代器,該迭代器以這種方式返回在該行中找到的每個字符串元素上調用int
整數構造函數的結果,最后從中創建一個子列表。
對文件中的每一行重復此過程,每次生成最終列表容器對象的子列表。
f = input("File name? ")
with open(f, encoding="UTF-8") as file:
data = [list(map(int, line.split())) for line in file]
print(data) # -> [[3, 2, 7, 4], [1, 8, 9, 3], [6, 5, 4, 1], [1, 0, 8, 7]]
with open('intFile.txt') as f:
res = [[int(x) for x in line.split()] for line in f]
with open('intList.txt', 'w') as f:
f.write(str(res))
添加到接受的答案。 如果要將該列表寫入文件,則需要打開文件並寫入字符串,因為write
只接受字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.