首页 > 解决方案 > Python - how to split a file object up into a list of individual characters?

问题描述

I'm importing data from a file object. It's pretty simple; it's a .txt file, and the data was entered like this: ABCDEFGHIJKLMNOPQRSTUVWXYZ

I am trying to get it to be a list of individual characters, e.g.

my_list = ['A', 'B', 'C', 'D', ...etc.]

but it's showing up like this:

my_list = ['ABCDEFGHIBJK... etc.]

Where am I going wrong?

def split(string): 
    return [char for char in string] 

# This opens a file, gets a file object, and returns it to the program.
def get_file_object1():
    infile = open(r'#', 'r')
    file_object = infile.readlines()

    testing = split(file_object)   # this is a test line
    print(testing)                 # this is a test line
    print(split('This is another test.'))

    infile.close()
    return file_object

Note: when I pass the file object to split(file_object), I get this

['ABCDEFGHIJKLMNOPQRSTUVWXYZ']

But when I pass a string of text to split('This is another string.'), I get this:

['T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', 'n', 'o', 't', 'h', 'e', 'r', ' ',
 't', 'e', 's', 't', '.']

标签: pythonpython-3.x

解决方案


简单,只需阅读并申请list();-)

with open(r'C:\Users\Liz\Desktop\PYTHON PROBLEMS\cipherUpper.txt') as f:
  myList = list(f.read().strip())

获取myList您的清单


推荐阅读