0

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?

1
  • use 'f1.readline() Commented Apr 20, 2016 at 4:44

5 Answers 5

2

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]) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, for the clear and simple explanation. It works like a charm
1

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]

Comments

1

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]) 

Comments

1

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.

Comments

1

the readlines return a list

use test[0] for substring

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.