Reputation: 75
I have the following code in a text file:
Host: 0.0.0.0 Port: 80
This is my python code:
with open('config.txt', 'r') as configfile:
lines = configfile.readlines()
lines.split(': ')
HOST = lines[1]
PORT = lines[3]
print(f'Your host is {HOST} and port is {PORT}')
But I get this error:
Traceback (most recent call last):
File "test.py", line 3, in <module>
lines.split(': ')
AttributeError: 'list' object has no attribute 'split'
How can I fix this? I'm fairly new to python
Upvotes: 2
Views: 458
Reputation: 453
Simple fix:
readline()
instead of readlines()
lines = lines.split(": ")
Reason:
readline()
returns a line from our file in the form of a stringreadlines()
returns all the lines from our file in the form of
list/array of stringslines
variable
with the returned result.Fixed Code:
with open('config.txt', 'r') as configfile:
lines = configfile.readline()
lines = lines.split(': ')
HOST = lines[1].split()[0]
PORT = lines[2]
print("Your host is {HOST} and port is {PORT}".format(HOST = HOST, PORT = PORT))
Config.txt:
Host: 0.0.0.0 Port: 80
Output:
Your host is 0.0.0.0 and port is 80
Upvotes: 0
Reputation: 344
The readlines() method returns a list. You can't do a split on an entire list.
You should do something along the lines of the below, you may not need the for loop if there's not multiple lines in the text file. But, you will likely need it to read the entire text file.
with open('config.txt', 'r') as configfile:
lines = configfile.readlines()
for item in lines:
item.split(': ')
HOST = item[1]
PORT = item[3]
print(f'Your host is {HOST} and port is {PORT}')
You could also use the range function if you need to index different list strings
with open('config.txt', 'r') as configfile:
lines = configfile.readlines()
for i in range(0,len(lines):
split_string = lines[i].split(': ')
HOST = split_string [1]
PORT = split_string [3]
print(f'Your host is {HOST} and port is {PORT}')
Upvotes: 1
Reputation: 3856
There are two issues here:
readlines()
return a list of all the lines in the filesplit
returns a list, it's not an in-place operationwith open('config.txt', 'r') as configfile:
lines = configfile.readlines() # lines will be a list of all the lines in the file
line_split = lines[0].split(': ') # split returns a list, it's not an in-place operation
print(line_split)
HOST = line_split[1].split()[0]
PORT = line_split[2]
print(f'Your host is {HOST} and port is {PORT}')
Upvotes: 3