Python Forum
fileinput package appears to be zeroing files - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: fileinput package appears to be zeroing files (/thread-28026.html)



fileinput package appears to be zeroing files - rexrf - Jul-01-2020

trying to replace a string inline using fileinput package, but after being processed the resulting files are zero bytes... here is a snippet of code, if you need it all just ask :)

for i in files:
        try:
            with open(i) as f:
                data = f.read()
        except Exception as e:
            log_it(logfile, time.time(), "warn", str(e))
            print(e)
        if args.match in data:
            for line in fileinput.input(i, inplace=True, backup=".backup"):
                line = line.replace(args.match, args.replace)
        else:
            # file doesnt contain string, restart the loop
            continue

Fix was to add a print(line) after the replace() statement. Fileinput writes stdout to the file...