所以在Ruby中我可以做到以下幾點:逐行讀取文件中的行到一個數組中的元素在Python
testsite_array = Array.new
y=0
File.open('topsites.txt').each do |line|
testsite_array[y] = line
y=y+1
end
如何將一個做到這一點在Python?
所以在Ruby中我可以做到以下幾點:逐行讀取文件中的行到一個數組中的元素在Python
testsite_array = Array.new
y=0
File.open('topsites.txt').each do |line|
testsite_array[y] = line
y=y+1
end
如何將一個做到這一點在Python?
testsite_array = []
with open('topsites.txt') as my_file:
for line in my_file:
testsite_array.append(line)
這是可能的,因爲Python允許您直接遍歷文件。
或者,更簡單的方法,使用f.readlines()
:
with open('topsites.txt') as my_file:
testsite_array = my_file.readlines()
只要打開該文件,並使用readlines()
功能:
with open('topsites.txt') as file:
array = file.readlines()
在蟒可以使用文件對象的readlines
方法。
with open('topsites.txt') as f:
testsite_array=f.readlines()
或者乾脆用list
,這是一樣的使用readlines
但唯一不同的是,我們可以通過一個可選的大小參數readlines
:
with open('topsites.txt') as f:
testsite_array=list(f)
幫助上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.