954,546 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Newbie: problems deleting lines from text file (large)

hello,

i'm a newbie programmer (and to python, double trouble :) and running into issues reading and writing files. i'm successfully running the code below to manipulate and remove the first few lines of a text file. The text file (file1.txt) is approx. 329kb but when i run the code it only writes a new 5kb file (file2.txt)... so the other 300 something kb below that is missing. how can i get the full file (to file2.txt) with only the first 4 lines removed???

so confused... please help!! :)

lines = file('./simple-retrieval/file1.txt', 'r').readlines()
del lines[0:4]
file('./simpleunwrapped/file2.txt', 'w').writelines(lines)

Thanks in advance!!!

eemqjunk
Newbie Poster
2 posts since Apr 2008
Reputation Points: 10
Solved Threads: 0
 

Replace del lines[0:4] with lines = lines[4:]

vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

I get the same exact results :(

here's another thing i should throw in... if i comment out the "del lines" line the results are the same... the whole file is still not copying to the new location.

it looks like the whole file never really opens...

As far as opening the file... am i doing it correctly?? i had an impression that readlines() as opposed to readline() is suppose to read the whole file into memory... is this true?

eemqjunk
Newbie Poster
2 posts since Apr 2008
Reputation Points: 10
Solved Threads: 0
 

This works just fine for me using a Windows Vista machine:

lines = file('./simple-retrieval/file1.txt', 'r').readlines()

# show the first 10 lines for a test
print lines[:10]

del lines[0:4]

# now show the first 10 lines for a test
print lines[:10]

file('./simpleunwrapped/file2.txt', 'w').writelines(lines)
ZZucker
Master Poster
702 posts since Jan 2008
Reputation Points: 327
Solved Threads: 46
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You