Richard de Ree
Richard de Ree

Reputation: 2540

Python reading file and get a substring

I read a file which contains:

> hello world

Using the following code to read this file, but I can't read a part of it

with open("/home/pi/example1.txt") as f1:
    test = f1.readlines(0)
    print (test)
    print (test[0:2])

expected output:

Hello world
He

Output what I get

['helloworld\r\n']
['helloworld\r\n']

What is the right (and SIMPLE) way to get a part of a substring what I grab from a file?

Upvotes: 0

Views: 1607

Answers (5)

eric
eric

Reputation: 41

the readlines return a list

use test[0] for substring

Upvotes: 1

Strik3r
Strik3r

Reputation: 1057

You can use the .strip() function which is available to remove all the white space and new line characters from a string

    with open('../../xx.txt','r') as fi:
        for line in fi:
           print(line.strip())
           print(line[0:2])

I didn't used the .strip() method in the second print statement because we are just getting the initial part of a string . so it will not be a new line character(let's hope so). In case if you want you can use for that line also

    print(line[0:2].strip())

strip() method will be really helpful specially if you are using the string later for any comparison.

Upvotes: 1

Hassan Mehmood
Hassan Mehmood

Reputation: 1402

Here is the correct code that you want.

with open("/home/pi/example1.txt") as f1:
    test = f1.readlines(0)
    print (test[0])
    print (test[0][0:2])

But alternatively you can use the following approach.

with open("/home/pi/example1.txt") as f1:
    test = f1.readline()
    print (test)
    print (test[0:2])

Upvotes: 1

aroy
aroy

Reputation: 482

Just change a bit to :

with open("/home/pi/example1.txt") as f1:
    for test in f1:
        print(test)
        print(test[0:2])

Other way readline returns a list then just use the indexing line readline()[0]

Upvotes: 1

Burhan Khalid
Burhan Khalid

Reputation: 174624

readlines() returns a list, as you can see in your output the string is actually part of a one-item list:

>>> f = ['helloworld\r\n']
>>> f[0][0:2]
'he'

To fix your original code, you need to move the 0 after the readlines call:

test = f1.readlines()[0]

However, as you are using the with statement, your life is a lot simpler:

with open("/home/pi/example1.txt") as f1:
    for line in f1:
        print(line)
        print(line[0:2])

Upvotes: 2

Related Questions