Hey. I'm pretty new in Python. I'm trying to read from my file all the content and put it in a string. My file looks:

1 string1
2 string2
10 string 3

and I want to obtain: ["1", "string1", "2", "string 2", "10", "string3"] using this:

def read(self):
        file = open("Repository/file.txt", 'r')
        f = file.readlines()
        f = f.split(" ")
        print f

but I get this: AttributeError: 'list' object has no attribute 'split'

Thanks!

Dani AI

Generated

Short diagnosis: , the traceback comes from calling split on the list returned by file.readlines() — a list has no split method. pointed you toward reading the file as a string and splitting, and showed per-line splitting; both are valid starting points but have different effects (reading whole file flattens every token; per-line split gives pairs). That matters if the "string" part can contain spaces (your example shows both "string 3" and "string3").

A robust pattern that preserves the remainder of each line (including internal spaces) is to split only at the first separator. The example below uses partition so the left side is the number and the right side is the rest of the line:

result = []
with open('Repository/file.txt', 'r') as fh:
    for line in fh:
        line = line.rstrip('\n')
        if not line.strip():
            continue
        num, sep, rest = line.partition(' ')
        result.extend([num, rest])
print(result)

Notes and gotchas:

  • If the separator can be tabs or multiple spaces, use a first-whitespace split (parts = line.split(None, 1)) instead of partition.
  • If you instead get nested pairs (e.g. [['1','string1'], ...]) and want a flat list, flatten with flat = [token for pair in pairs for token in pair].
  • Handle missing fields (check rest before using), and skip blank lines as shown.
  • For very large files avoid read() / read().split() — iterate lines to keep memory use low.
  • The sample input/desired output is inconsistent for "10 string 3" vs "string3"; if you intend to remove internal spaces in the text field, apply rest = rest.replace(' ', '') after splitting.

This keeps the file reading explicit, preserves multi-word values, and avoids the AttributeError caused by treating a list like a string.

Recommended Answers

All 2 Replies

Use f = file.read() and f = f.split() .

commented: Very Helpful! Thanks. +0
with open('numb.txt') as f:
    print [i.split() for i in f]
    #[['1', 'string1'], ['2', 'string2'], ['10', 'string3']]

A little mistake like this for 1 list.

with open('numb.txt') as f:
    print f.read().split()
    #['1', 'string1', '2', 'string2', '10', 'string3']
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.