Home > OS >  How can I create an array from a .txt file?
How can I create an array from a .txt file?

Time:11-16

I have a txt file of only a continuous string of characters MNHY...

I want to have the output of ['M','N','H','Y'...]

I have attempted this code below and various forms of it, but I can only convert the txt file as one continuous list.

def text_check(filename):
    my_file = open(filename,"r")
    print(my_file.read().splitlines())
text_check("demo_text.txt")

How can I convert the .txt file to this ['M','N','H','Y'...] format?

CodePudding user response:

Assuming the file contains

MNYH…

you can use:

with open(filename) as f:
    out = list(f.read().strip())
print(out)

output: ['M', 'N', 'H', 'Y', '…']

CodePudding user response:

Simply use list() method.

The list() method in python will convert a continous string into seperate character.

In other words, the codes that work for you are:

def text_check(filename):
    my_file = open(filename,"r")
    li_chars = list(my_file.read().splitlines()[0])
    print(li_chars)
    my_file.close()
text_check("demo_text.txt")
  1. The list() method will do the spliting when it accepts a string, so I add [0] to splitlines().

  2. I add my_file.close() at the end of text_check().


Improvements

def text_check(filename):
    with open(filename,"r") as f:
        li_chars = list(f.read().splitlines()[0])
        print(li_chars)
text_check("demo_text.txt")

The with statement provides a way for ensuring that a clean-up is always used.

  • Related