Hướng dẫn python read file into array - python đọc tệp thành mảng

Vì vậy, bạn muốn tạo một danh sách các danh sách ... chúng ta cần bắt đầu với một danh sách trống

list_of_lists = []

Tiếp theo, chúng tôi đọc nội dung tệp, từng dòng

with open['data'] as f:
    for line in f:
        inner_list = [elt.strip[] for elt in line.split[',']]
        # in alternative, if you need to use the file content as numbers
        # inner_list = [int[elt.strip[]] for elt in line.split[',']]
        list_of_lists.append[inner_list]

Một trường hợp sử dụng phổ biến là dữ liệu cột, nhưng các đơn vị lưu trữ của chúng tôi là các hàng của tệp, mà chúng tôi đã đọc từng cái một, vì vậy bạn có thể muốn chuyển đổi danh sách danh sách của mình. Điều này có thể được thực hiện với thành ngữ sau

by_cols = zip[*list_of_lists]

Một cách sử dụng phổ biến khác là đặt tên cho mỗi cột

col_names = ['apples sold', 'pears sold', 'apples revenue', 'pears revenue']
by_names = {}
for i, col_name in enumerate[col_names]:
    by_names[col_name] = by_cols[i]

để bạn có thể hoạt động trên các mục dữ liệu đồng nhất

 mean_apple_prices = [money/fruits for money, fruits in
                     zip[by_names['apples revenue'], by_names['apples_sold']]]

Hầu hết những gì tôi đã viết có thể được tăng tốc bằng mô -đun

with open['data'] as f:
    for line in f:
        inner_list = [elt.strip[] for elt in line.split[',']]
        # in alternative, if you need to use the file content as numbers
        # inner_list = [int[elt.strip[]] for elt in line.split[',']]
        list_of_lists.append[inner_list]
4, từ thư viện tiêu chuẩn. Một mô -đun bên thứ ba khác là
with open['data'] as f:
    for line in f:
        inner_list = [elt.strip[] for elt in line.split[',']]
        # in alternative, if you need to use the file content as numbers
        # inner_list = [int[elt.strip[]] for elt in line.split[',']]
        list_of_lists.append[inner_list]
5, cho phép bạn tự động hóa hầu hết các khía cạnh của phân tích dữ liệu điển hình [nhưng có một số phụ thuộc].

Cập nhật trong khi ở Python 2

with open['data'] as f:
    for line in f:
        inner_list = [elt.strip[] for elt in line.split[',']]
        # in alternative, if you need to use the file content as numbers
        # inner_list = [int[elt.strip[]] for elt in line.split[',']]
        list_of_lists.append[inner_list]
6 trả về một danh sách khác nhau [được chuyển đổi], trong Python 3, tình huống đã thay đổi và
with open['data'] as f:
    for line in f:
        inner_list = [elt.strip[] for elt in line.split[',']]
        # in alternative, if you need to use the file content as numbers
        # inner_list = [int[elt.strip[]] for elt in line.split[',']]
        list_of_lists.append[inner_list]
6 trả về một đối tượng zip không thể đăng ký.

Nếu bạn cần truy cập được lập chỉ mục, bạn có thể sử dụng

by_cols = list[zip[*list_of_lists]]

Điều đó cung cấp cho bạn một danh sách các danh sách trong cả hai phiên bản của Python.

Mặt khác, nếu bạn không cần truy cập được lập chỉ mục và những gì bạn muốn chỉ là xây dựng một từ điển được lập chỉ mục bằng tên cột, một đối tượng zip vẫn ổn ...

file = open['some_data.csv']
names = get_names[next[file]]
columns = zip[*[[x.strip[] for x in line.split[',']] for line in file]]]
d = {}
for name, column in zip[names, columns]: d[name] = column

Phương pháp 1 [SQA]

  • Phương pháp này sử dụng các mảng của các mảng có kích thước và kiểu dữ liệu được đặt.
  • Tệp được mở và đóng một cách rõ ràng
  • Chương trình sẽ bị sập nếu không có đủ các dòng dữ liệu trong tệp
# define filename as a constant
DATA_FILE= 'students.csv'
NUMBER_OF_STUDENTS = 20

def readDataFromFile[]:  
    # create empty arrays
    names = [""] * NUMBER_OF_STUDENTS
    marks = [0] * NUMBER_OF_STUDENTS
 
    # open file for reading
    f=open[DATA_FILE, 'r']
 
    for line in range[NUMBER_OF_STUDENTS]:
        # decode each line from file
        data = f.readline[]
        data = data.strip['n']
        data = data.split[',']
 
        # insert data into arrays
        names[line] = data[0]
        marks[line] = int[data[1]]
 
    f.close[]
  
    return names, marks
 
#MAIN PROGRAM
names, marks= readDataFromFile[]
print[name, mark]

Phương pháp 2 [Pythonic]

  • Phương pháp này nối dữ liệu vào danh sách
  • Tệp được đóng tự động khi vòng lặp hoàn thành
# define filename as a constant
DATA_FILE= 'students.csv'

def readDataFromFile[]:  
    # create empty lists
    names = []
    marks = []
 
    # open file for reading
    with open[DATA_FILE, 'r'] as f:
        for line in f.readlines[]:

            # decode each line from file
            data = line.strip['n']
            data = data.split[',']
 
            # add data to lists
            names.append[data[0]]
            marks.append[int[data[1]]]
 
    return names, marks
 
#MAIN PROGRAM
names, marks= readDataFromFile[]
print[name, mark]

Bạn có thể sử dụng một trong hai phương thức sau để đọc tệp văn bản vào danh sách trong Python:

Phương pháp 1: Sử dụng Open [] & NBSP;

#define text file to open
my_file = open['my_data.txt', 'r']

#read text file into list
data = my_file.read[]

Phương pháp 2: Sử dụng LoadTXT [] & NBSP;

with open['data'] as f:
    for line in f:
        inner_list = [elt.strip[] for elt in line.split[',']]
        # in alternative, if you need to use the file content as numbers
        # inner_list = [int[elt.strip[]] for elt in line.split[',']]
        list_of_lists.append[inner_list]
0

Các ví dụ sau đây cho thấy cách sử dụng từng phương pháp trong thực tế.

Ví dụ 1: Đọc tệp văn bản vào danh sách bằng Open []

Mã sau đây cho thấy cách sử dụng hàm Open [] để đọc tệp văn bản có tên my_data.txt vào một danh sách trong Python:open[] function to read a text file called my_data.txt into a list in Python:

with open['data'] as f:
    for line in f:
        inner_list = [elt.strip[] for elt in line.split[',']]
        # in alternative, if you need to use the file content as numbers
        # inner_list = [int[elt.strip[]] for elt in line.split[',']]
        list_of_lists.append[inner_list]
1

Ví dụ 2: Đọc tệp văn bản vào danh sách bằng LoadTXT []

Mã sau đây cho thấy cách sử dụng hàm numpy loadtxt [] để đọc tệp văn bản có tên my_data.txt thành một mảng numpy:loadtxt[] function to read a text file called my_data.txt into a NumPy array:

with open['data'] as f:
    for line in f:
        inner_list = [elt.strip[] for elt in line.split[',']]
        # in alternative, if you need to use the file content as numbers
        # inner_list = [int[elt.strip[]] for elt in line.split[',']]
        list_of_lists.append[inner_list]
2

Điều tuyệt vời khi sử dụng LoadTXT [] là chúng ta có thể chỉ định kiểu dữ liệu khi nhập tệp văn bản bằng cách sử dụng đối số DTYPE.loadtxt[] is that we can specify the data type when importing the text file by using the dtype argument.

Ví dụ: chúng tôi có thể chỉ định tệp văn bản được nhập vào một mảng numpy dưới dạng số nguyên:

with open['data'] as f:
    for line in f:
        inner_list = [elt.strip[] for elt in line.split[',']]
        # in alternative, if you need to use the file content as numbers
        # inner_list = [int[elt.strip[]] for elt in line.split[',']]
        list_of_lists.append[inner_list]
3

Lưu ý: Bạn có thể tìm thấy tài liệu đầy đủ cho hàm LoadTXT [] ở đây.: You can find the complete documentation for the loadtxt[] function here.

Tài nguyên bổ sung

Các hướng dẫn sau đây giải thích cách đọc các tệp khác trong Python:

Cách đọc tệp CSV với Numpy Cách đọc các tệp CSV có gấu trúc Cách đọc tệp văn bản có gấu trúc
How to Read CSV Files with Pandas
How to Read a Text File with Pandas

Làm cách nào để đọc một tệp văn bản đến một mảng trong Python?

Cách đọc một tập tin vào mảng trong Python..
DEF READFILE [Tên tệp]:.
fileObj = open [fileName, "r"] #opens tệp trong chế độ đọc ..
Words = FileObj.đọc[].splitlines [] #puts tệp vào một mảng ..
FileObj.gần[].
trả lại từ ..

Làm cách nào để đọc một tệp văn bản vào một mảng?

Để đọc một tệp văn bản vào một mảng:..
Sử dụng fspromise.Phương thức readFile [] để đọc nội dung của tệp ..
Chờ đợi lời hứa rằng phương pháp trở lại ..
Sử dụng chuỗi.Phương thức chia [] để chia chuỗi thành một mảng của chuỗi con ..

Làm cách nào để đọc một tệp văn bản vào một danh sách trong Python?

Sử dụng tệp ...
my_file = open ["sample.txt", "r"].
content_list = my_file.Đoạn đọc [].
print[content_list].

Làm thế nào để bạn đọc một tập tin trong Python và lưu trữ nó trong một danh sách?

Để đọc các tệp, hãy sử dụng phương thức Readlines [].Khi bạn đã đọc một tệp, bạn sử dụng Split [] để biến các dòng đó thành một danh sách.use the readlines[] method. Once you've read a file, you use split[] to turn those lines into a list.

Chủ Đề