Reputation: 9702
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
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
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