Delete data from file python




















Active 3 years, 5 months ago. Viewed times. Improve this question. Reblochon Masque Zeef Zeef 1. Please make a tiny effort searching for an existing answer before asking. You want to delete tags or show the values in the tag?

Add a comment. Active Oldest Votes. Improve this answer. Once that line has been read the cursor is now past it. When you try to write into the file you write where the cursor currently is.

By re-opening the file you reset the cursor. This task can be done opening the file only once Show 2 more comments. Solution to this problem with only a single open: with open "target.

Lother Lother 1, 1 1 gold badge 11 11 silver badges 17 17 bronze badges. This worked very well for me, as I had to use lockfile also fcntl. I couldnt find any way to use fileinput together with fcntl. It would be nice to see some side effects of this solution.

I wouldn't do this. If you get an error in the for loop, you'll end up with a partially overwritten file, with duplicate lines or a line half cut off.

You might want to f. That way if you get an error you'll just end up with an incomplete file. But the real solution if you have the disk space is to output to a temporary file and then use os. Might you add i. Because just i didn't do anything for me — Mangohero1.

In one loop and one only you can do the same thing. It will be much faster. Anonyme 74 1 1 silver badge 7 7 bronze badges. Barnabe Barnabe 5 5 silver badges 17 17 bronze badges. Instead of using normal for loop we can make use of Generator Expression This way program will not load all the lines from file to memory which is not good idea in case of big files. It will only have single line in memory at a time. With generator expression for loop will look like, output.

ShriShinde You're not reading the file into memory when looping over the file object either, so this solution works identical to your suggestion. You might want to delete the original file and rename the second file to the original file's name, which with Python on a Linux OS would look like this, subprocess.

Otherwise instead of overwriting the file you'll append the file to itself without the lines you're excluding. Deep Deep 9 9 silver badges 17 17 bronze badges. Add a comment. Active Oldest Votes. The Overflow Blog. Stack Gives Back Safety in numbers: crowdsourcing data on nefarious IP addresses.

Featured on Meta. New post summary designs on greatest hits now, everywhere else eventually. Linked Please use ide.

Load Comments. What's New. Most popular in Blogathon. How to Install Tkinter in Windows? Most visited in Python. We use cookies to ensure you have the best browsing experience on our website.



0コメント

  • 1000 / 1000