1

I have a text file which has three lines. I want to read those three lines as L1, L2 and L3 and count the character of L1, L2 and L3 as n1, n2 and n3. I tried as follows:

     f=open(sys.argv[1],'r')
     L1=f.readline()   
     L2=f.readline()   
     L3=f.readline()  
     if L1[-1]=='\n': L1=L1[:len(L1)-1] 
     if L2[-1]=='\n': L2=L2[:len(L2)-1] 
     if L3[-1]=='\n': L3=L3[:len(L3)-1] 
     n1=len(L1); n2=len(L2); n3=len(L3) 
     print L1, n1, L2, n2, L3, n3

The above script is working fine. But I wanted to know if there is a better/easier way to get L1, L2 and L3. Thanks in advance!

user2176228
  • 327
  • 3
  • 10

5 Answers5

1

You could:

  • Add exception handling using try-catch IOError for any problem opening the file and reading from it. See Errors and Exceptions Tutorial - or use the with statement for newer versions of Python as suggested by other answers.
  • Add exception handling using try-catch IndexError to handle the case where not enough arguments are given.
  • Do the check for newline with string.rstrip or string.strip for brevity.
  • Store the values in an array as suggested by other answers (you might want to terminate after 3 lines in case you get the wrong file and end up reading a very large file into memory).
D.J.Duff
  • 1,565
  • 9
  • 14
1

How about this:

with open(sys.argv[1]) as f:
  L1, L2, L3 = (line.rstrip() for line in f.readlines()[:3])

But you should really use lists...

erlc
  • 652
  • 1
  • 6
  • 11
0

The best way in my opinion is try putting them in an array. I dont use python but thats what ill do in c++

PopperJuan
  • 175
  • 1
  • 16
0

sure..

lines = []
with open(sys.argv[1], "r") as file:
    for line in file.readlines():
        if line[-1] == "\n":
            line = line[:-1]
        lines.append(line)

This way it doesn't matter how many lines you have in your file. Your program will still run until the end

Greg
  • 5,422
  • 1
  • 27
  • 32
0

I searched in stackoverflow and found a code that is simpler. It saves the content into an array:

with open(fname) as f:
    content = f.readlines()

If you want to strip the \n:

with open(fname) as f:
    content = [line.strip() for line in f]
Community
  • 1
  • 1
cwhy
  • 56
  • 5