简体   繁体   中英

Check if text file is empty

It's a script to move a file to another directory. How can I implement a checker, that checks if 'LiveryPath.txt' and 'OutputPath.txt' is empty?

import shutil
import ctypes
import time

with open("LiveryPath.txt","r") as f:
    Livery = f.read()

with open("Output.txt","r") as g:
    Output = g.read()

root_src_dir = Livery
root_dst_dir = Output


for src_dir, dirs, files in os.walk(root_src_dir):
    dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
    for file_ in files:
        src_file = os.path.join(src_dir, file_)
        dst_file = os.path.join(dst_dir, file_)
        if os.path.exists(dst_file):
            if os.path.samefile(src_file, dst_file):
                continue
            os.remove(dst_file)
        shutil.move(src_file, dst_dir)
time.sleep(3)
ctypes.windll.user32.MessageBoxW(0, "Your Livery is now installed!", "Success!", 64) ```

f.read() and g.read() return the content of your 2 files. So you just have to check if f.read() and g.read() are empty, ie if they are equal to '' .

Here is an example code:

with open('file.txt') as file:
    content = file.read()
    if content == '':
        print(f'the file {file.name} is empty.')
    else:
        print(f'the file {file.name} is not empty. Here is its content:\n{content}')

I would try this:

import os


if (os.stat('LiveryPath.txt').st_size == 0) and (os.stat('OutputPath.txt').st_size == 0):
   # do something

If you want to check if the file is empty or not, the size of the file can be checked. There can be couple of more options as well but this one is quite handy.

To achieve it the os utility can be used.

Example implementation

import os

def size_checker(filename):
    if os.stat(filename).st_size:
        return False
    else:
        return True

Happy Coding!

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