简体   繁体   中英

Reading characters from file into list

I have a part of a program with the following code

file1 = [line.strip()for line in open(sometext.txt).readlines()] 
print ((file1)[0])

and when the code is executed it gives me the whole contents of the txt file which is a very long sentence, how would I go about reading every letter and placing it in a list to index each character separately? I have used the list() function which seems to put the whole text file into a list and not each character.

You can use file.read() rather than file.readlines() :

file1 = [char for char in open(sometext.txt).read()]

You don't really need list-comprehension, however; instead you can do this:

file1 = list(open(sometext.txt).read())

Also, as @furas mentioned in his comment, you don't need a list to have indexing. str also has a method called index , so you could say file1 = open(sometext.txt).read() and still be able to use file1.index() . Note, str also has a find method which will return -1 if the substring is not found, rather than raising a ValueError.

With a read() is enough. Plus. if you want to store the list without \\n and white spaces, you can use:

char_list = [ch for ch in open('test.txt').read() if ch != '\n' if ch != ' ']

You can remove the if statements if you want to maintain them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM