user5007666
user5007666

Reputation:

Parsing the text in a file

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

Upvotes: 1

Views: 53

Answers (4)

ricknroll
ricknroll

Reputation: 66

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

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49318

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

Upvotes: 1

wallyk
wallyk

Reputation: 57774

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.

Upvotes: 1

Joe T. Boka
Joe T. Boka

Reputation: 6583

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

Upvotes: 1

Related Questions