Read and convert row in text file into list of string

Viewed 4317

I have a text file data.txt that contains 2 rows of text.

first_row_1    first_row_2    first_row_3
second_row_1    second_row_2    second_row_3

I would like to read the second row of the text file and convert the contents into a list of string in python. The list should look like this;

txt_list_str=['second_row_1','second_row_2','second_row_3']

Here is my attempted code;

import csv
with open('data.txt', newline='') as f:
    reader = csv.reader(f)
    row1 = next(reader)
    row2 = next(reader)

my_list = row2.split("  ")

I got the error AttributeError: 'list' object has no attribute 'split'

I am using python v3.

EDIT: Thanks for all the answers. I am sure all of them works. But can someone tell me what is wrong with my own attempted code? Thanks.

3 Answers

The reason your code doesn't work is you are trying to use split on a list, but it is meant to be used on a string. Therefore in your example you would use row2[0] to access the first element of the list.

my_list = row2[0].split("    ")

Alternatively, if you have access to the numpy library you can use loadtxt.

import numpy as np

f = np.loadtxt("data.txt", dtype=str, skiprows=1)

print (f)
# ['second_row_1' 'second_row_2' 'second_row_3']

The result of this is an array as opposed to a list. You could simply cast the array to a list if you require a list

print (list(f))
#['second_row_1', 'second_row_2', 'second_row_3']

Use read file method to open file.

E.g.

>>> fp = open('temp.txt')

Use file inbuilt generator to iterate lines by next method, and ignore first line.

>>> next(fp)
'first_row_1    first_row_2    first_row_3)\n'

Get second line in any variable.

>>> second_line = next(fp)
>>> second_line
'second_row_1    second_row_2    second_row_3'

Use Split string method to get items in list. split method take one or zero argument. if not given they split use white space for split.

>>> second_line.split()
['second_row_1', 'second_row_2', 'second_row_3']

And finally close the file.

fp.close()

Note: There are number of way to get respective output. But you should attempt first as DavidG said in comment.

with open("file.txt", "r") as f:
    next(f)    # skipping first line; will work without this too
    for line in f:
        txt_list_str = line.split()
print(txt_list_str)

Output

['second_row_1', 'second_row_2', 'second_row_3']
Related