Home > Back-end >  Python Read strings from file
Python Read strings from file

Time:01-16

Unfortunately I have the problem that I can not read strings from files, the part of the code would be:

names = ["Johnatan", "Jackson"]

i tried it with this = open("./names.txt", "r") instead of (code above) but unfortunately this does not work, if I query it without the file it works without problems.

I would be very happy if someone could help me and tell me exactly where the problem is.

CodePudding user response:

f = open('./names.txt', 'r', encoding='utf-8')
words_string = f.readlines()
words = words_string.split(',')

print(words)

I hope it helps.. As your file contains all the words with comma-separated using readlines we get all the lines in the file as a single string and then simply split the string using .split(','). This results in the list of words that you need.

CodePudding user response:

try read the data in the file like this:

with open(file_path, "r") as f:
    data = f.readlines()

data = ['maria, Johnatan, Jackson']

inside data is the list of name. you can parse it using split(",")

CodePudding user response:

you can split in lines if you have in the file, Johnatan,Jackson,Maria doing:

with open("./names.txt", "r", encoding='utf-8') as fp:
    content = fp.read()
    names = content.split(",")

you can also do:

names = open("./names.txt", "r", encoding='utf-8').read().split(",")

if you want it to be oneliner,

  •  Tags:  
  • Related