Problem in python using readline data into an array
so here my code
arr = []
inp = open ("test.txt","r")
for line in inp.readlines():
for i in line.split():
arr.append(i)
print arr
and the output for arr is [开发者_如何学JAVA] and if i try to print arr[0] or anything it says the index is out of range im trying to take the data out of the text and put it into array for use or even a list i could read the data off of ive tried alot ways this seemed to be the easiest in my wrong opinion i guess lol
all since im here asking id also like to search that document for a line that starts with say "start" and but that data into the array or list what might be the best way to go about that and thanks for the help also im new to python and its really late so this is my last resort
There is no need to call .readlines()
. The open()
function returns a file handle that works as an iterator, and it will return one line at a time. Also, if you are using a modern Python you have with
and it is best practice to use it for this sort of thing. So:
arr = []
with open("test.txt", "r") as inp:
for line in inp:
for word in line.split():
arr.append(word)
print arr
This looks perfectly good to me, and when I tested it, it worked for me.
P.S. I can't resist doing it as a one-line list comprehension:
arr = [word for line in open("test.txt") for word in line.split()]
print arr
Eh, even the list comprehension should be using with()
. So:
with open("test.txt", "r") as inp:
arr = [word for line in inp for word in line.split()]
print arr
The code is all right. Either test.txt
is empty, or this is not the right piece of code, or you have edited something important out of it.
I'm assuming you want the list to contain each line of the file. In this case you do not need the extra 'if' inside the loop as the readlines method will already read the file one line at a time.
The array will be empty if the file is empty.
Also to only add lines that start with "start" into the array you could do something like this:
arr = []
inp = open("test.txt","r")
for line in inp.readlines():
if line.startswith("start"):
arr.append(line)
print arr
Or even shorter code:
arr = [x for x in open('text.txt') if x.startswith('start')]
精彩评论