2017-12-27 99 views
0

我從txt文件中讀取元素,並且想要將元素寫入數組,我知道我必須使用substring方法,但我不知道如何生成數組使用子串方法。如何在Python中將元素寫入數組

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種元素的多維(5×6)陣列,可以閱讀使用此代碼此文件的元素但我不知道如何將它們寫入數組。

+1

看'](https://docs.python.org/2/library/string.html#string.split)和['str.strip'](https://docs.python.org/2/library/string。 html#string.strip) – schwobaseggl

回答

2

爲了得到多維數組,你需要逐行讀取文件中的行,並用逗號在我previous answer

# 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) 
+0

我收到一個錯誤 – hbakan

+0

修正了它。據說,解決這個錯誤將是你的功課:) – MihanEntalpo

+0

非常感謝,我瞭解到我應該做的。 – hbakan

1

您需要作爲字符串來讀取數據,並在由逗號和換行符把它分解:

# Open file 
with open("example.txt", "r") as f: 
    # read the contents and replace "\n" characters by commas 
    thedata = f.read().replace("\n", ",") 
    # split it by "," creating an array 
    array = thedata.split(",") 
    # if it's needed, remove empty elements and trim spaces: 
    array = [item.strip() for item in array if item.strip() != ""] 
# Printing result: 
print(array) 
+0

你也應該考慮這些行。 – schwobaseggl

+0

看起來像這樣,但問題的作者說:「我需要生成30個元素數組」,我已經回答了這個需求:) – MihanEntalpo

+0

如果你只用逗號分割,我認爲你不會得到滿30 ;) – schwobaseggl

2

所有你需要的是沿str.split()str.strip()爲:

with open("example.txt") as f: 
    my_list = [w.strip() for l in f for w in l.split(',')] 
#    ^to remove extra white-spaces 

這將返回my_list列表爲:

>>> my_list 
['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'] 
+3

這是最乾淨和最Pythonic的方法! – schwobaseggl

3

你可以這樣做,使用split

In [14]: print map(str.strip,sum([i.split(',') for i in open("example.txt").split('\n')],[])) 
['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'] 

不同的方法壓扁名單,

result = map(str.strip,[item for sublist in [i.split(',') for i in txt.split('\n')] for item in sublist]) 
+2

男孩,我愛那些Python單行:) – noamgot

+0

但是請注意,列出展平的總和方法具有二次時間複雜性。你也不會剝奪空間。 – schwobaseggl

+0

@schwobaseggl感謝您的意見, –

2

很多體面的理解基於解決方案的周圍。下面是一個使用mapitertools.chain

from itertools import chain 
with open("example.txt", "r") as f: 
    array = list(chain(*(map(str.strip, line.split()) for line in f))) 
0

分割每行,就像如果你想爲了保持CSV文件的格式,並有一個二維數組,然後可能先設置二維數組,然後遍歷文件並添加值可能是要走的路。

array = [] 

for row in range(0,6): 
    array.append([]) 
    for col in range(0,5): 
     array[row].append(" ") 

print(array) 

然後添加你瓦萊斯而不是用空間,導入的文件,通過各行進行迭代,併爲每個值在它[`str.split添加到相應的空間,在你的二維數組