I am trying to read text files in a directory. However before doing any action I want to make sure it is not empty. If the text file is empty I need to create that empty file again (in the current directory that is), if not I need to perform some calculations with the each line of the text file and create corresponding file with same name. In short, I need to create as many files as the referred directory (path_in
) has.
So to check if the text file is empty I thought I should open it first. I opened it with open
and its handle is filename_handle
. I checked if it is empty, but here it raises TypeError: argument should be string, bytes or integer, not _io.TextIOWrapper
. I know why this error occured (because filename_handle
is object), but I don't know the other way of how I can check if the file is empty.
Can someone help me how to fix this.
Here is my code
import numpy as np
import cv2, os
from glob import glob
path_in = 'C:\\Users\\user\\Desktop\\labels'
for filename in os.listdir(path_in):
filename_edited = []
with open(path_in + '\\' +filename) as filename_handle:
if os.stat(filename_handle).st_size == 0:
filename_edited.append(filename_handle)
else:
for line in filename_handle:
numericdata = line.split(' ')
numbers = []
for i in numericdata:
numbers.append(int(i))
c,x,y = numbers
edited = [c, y, (19-x)]
filename_edited.append(edited)
filename_edited_array = np.array(filename_edited)
with open(filename , 'wb') as f:
np.savetxt(f, filename_edited_array,fmt= '%.1i', delimiter=' ', newline='\n', header='', footer='', comments='# ')
continue