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]
# 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]
# 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]
0Cá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]
1Ví 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]
3Lư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