Ratha
Ratha

Reputation: 9702

Line.strip() is not working in python?

I try to remove a whitespace line in my file; But it is not removing my white space line.

def removeWhiteSpaceLine():
    fp = open("singleDataFile.csv")
    for i, line in enumerate(fp, 1):
        if i == 2:
            line.strip()
    fp.close()

My sample file is like:(i want to remove the 2nd line which is white space)

Name,Address,Age

John,Melbourne,28
Kati,Brisbane,35
.....

Upvotes: 0

Views: 1087

Answers (3)

Maxime Chéramy
Maxime Chéramy

Reputation: 18861

line.strip() do not modify line but returns a new string.

Calling line.strip() alone on its line has no effects. You must reassign the result to your variable:

line = line.strip()

However, it looks like you shouldn't use strip anyway:

strip()

Return a copy of the string with leading and trailing characters removed.

To me, it's unclear what you're asking:

1) fp = open("singleDataFile.csv") opens the file in read only mode. If you expect to update the file, that won't work. If you want to modify the file, open it in write mode ("w" or "r+").

2) Maybe you don't want to modify the file but only ignore the second line? In that case, you should add all the lines in a list and ignore that second line.

with open("singleDataFile.csv", "r+") as f:
    content = f.readlines() # read content
    f.seek(0) # go back to the begin of the file
    for i, line in enumerate(content):
        if i != 1: # the condition could also be if line.strip()
            f.write(line) # write all lines except second line
    f.truncate() # end of file

Upvotes: 2

Vikas Periyadath
Vikas Periyadath

Reputation: 3186

Try like this, Here modifying the same file like rewriting same contents to same file except blank lines:

with open("singleDataFile.csv","r") as f:
    lines=f.readlines()

with open("singleDataFile.csv","w") as f:  
    for line in lines:
        if line.strip():
           f.write(line) 

Upvotes: 0

Jitesh Vacheta
Jitesh Vacheta

Reputation: 85

try using pandas library.

pd.colname.str.strip()

Upvotes: 0

Related Questions