2013-04-25 48 views

Trả lời

12
testsite_array = [] 
with open('topsites.txt') as my_file: 
    for line in my_file: 
     testsite_array.append(line) 

Điều này có thể vì Python cho phép bạn duyệt qua các tập tin trực tiếp.

Ngoài ra, phương pháp đơn giản hơn, sử dụng f.readlines():

with open('topsites.txt') as my_file: 
    testsite_array = my_file.readlines() 
5

Chỉ cần mở tập tin và sử dụng các chức năng readlines():

with open('topsites.txt') as file: 
    array = file.readlines() 
5

Trong python bạn có thể sử dụng phương pháp readlines của một đối tượng tập tin.

with open('topsites.txt') as f: 
    testsite_array=f.readlines() 

hoặc đơn giản là sử dụng list, đây là giống như sử dụng readlines nhưng sự khác biệt duy nhất là chúng ta có thể vượt qua một đối số tùy chọn kích thước để readlines:

with open('topsites.txt') as f: 
    testsite_array=list(f) 

giúp đỡ về file.readlines:

In [46]: file.readlines? 
Type:  method_descriptor 
String Form:<method 'readlines' of 'file' objects> 
Namespace: Python builtin 
Docstring: 
readlines([size]) -> list of strings, each a line from the file. 

Call readline() repeatedly and return a list of the lines so read. 
The optional size argument, if given, is an approximate bound on the 
total number of bytes in the lines returned. 
Các vấn đề liên quan