检查文本文件是否为空

时间:2020-08-22 16:00:53

标签: python

这是一个将文件移动到另一个目录的脚本。 如何实现检查器,检查“ LiveryPath.txt”和“ OutputPath.txt”是否为空?

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) ```

3 个答案:

答案 0 :(得分:1)

f.read()g.read()返回2个文件的内容。 因此,您只需要检查f.read()g.read()是否为空,即它们是否等于''

这是示例代码:

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}')

答案 1 :(得分:1)

我会尝试:

import os


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

答案 2 :(得分:0)

如果要检查文件是否为空,可以检查文件的大小。也可以有更多其他选择,但这很方便。

要实现此目的,可以使用os实用程序。

示例实现

import os

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

快乐编码!