简体   繁体   中英

Python file handling and lines input

If i have a python file let's say abc.txt and contains the following data ONLY

    #data(data may change dynamically)
    #data(data may change dynamically)

I want to delete the file itself. (abc.txt)

But what if there's a python file which is still the same file containing the data AND something else, I will want to keep the file. (abc.txt)

    #12345 (Number may change dynamically)
    #46346346 (Number may change dynamically)

    DATA
    DATA
    DATA

Is there anyway i can do this? Sorry I am really new to python and I can't figure out a way to delete the file itself because of the ever-changing conditions.

This code works:

import os

def remove_file(filename):
    with open(filename, 'r') as f:
        for line in f:
            line = line.strip()
            if line and not line.startswith('#'):
                return False

    os.remove(filename)
    return True

if __name__ == '__main__':
    if remove_file('abc.txt'):
        print 'File was removed!'
    else:
        print 'File was not removed!'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM