1

I am trying print the contents of a text file using below code,the text file will only contain one line,my current output is as below which is a list with "\r\n" at the end,I want to the output to be as shown in "EXPECTED OUTPUT" ?

branch_textfile = branch + '.txt' with open(branch_textfile, 'r') as f: #open the file contents = f.readlines() #put the lines to a variable (list). #contents = contents.rstrip() print contents 

CURRENT OUTPUT:-

['AU_TEST_PUBLIC_BRANCH.05.01.01.151.005\r\n'] 

EXPECTED OUTPUT:-

AU_TEST_PUBLIC_BRANCH.05.01.01.151.005 
1
  • The culprit is readlines() - it's not the right method for the job here. Commented Jul 9, 2015 at 0:23

4 Answers 4

1
>>> x = ['AU_TEST_PUBLIC_BRANCH.05.01.01.151.005\r\n'] >>> print x[0].rstrip() AU_TEST_PUBLIC_BRANCH.05.01.01.151.005 >>> 
Sign up to request clarification or add additional context in comments.

Comments

1

It does that because f.readlines() returns an array (or is it a list?) Either way, you can avoid the brackets with:

print contents[0] 

This works but it only prints the first line of the file.

1 Comment

A list would be the proper term for python.
1

Use contents = f.read().rstrip() instead of contents = f.readlines(). This will read the file into a single string and remove the trailing whitespace.

Comments

1

why did you "#" the .rstrip() out? it is the right command!

you can also put that on the end of the statment like this:

with open('file','r') as f: data = f.read().strip() 

Comments