텍스트 파일이 있습니다.
비어 있는지 여부를 어떻게 확인할 수 있습니까?
답변
>>> import os
>>> os.stat("file").st_size == 0
True
답변
import os
os.path.getsize(fullpathhere) > 0
답변
모두 getsize()
와 stat()
파일이 존재하지 않는 경우 예외가 발생합니다. 이 함수는 던지지 않고 True / False를 반환합니다 (단순하지만 덜 강력 함).
import os
def is_non_zero_file(fpath):
return os.path.isfile(fpath) and os.path.getsize(fpath) > 0
답변
어떤 이유로 든 파일을 이미 열었다면 다음을 시도하십시오.
>>> with open('New Text Document.txt') as my_file:
... # I already have file open at this point.. now what?
... my_file.seek(0) #ensure you're at the start of the file..
... first_char = my_file.read(1) #get the first character
... if not first_char:
... print "file is empty" #first character is the empty string..
... else:
... my_file.seek(0) #first character wasn't empty, return to start of file.
... #use file now
...
file is empty
답변
ghostdog74의 답변 과 의견을 결합하여 재미있게 사용하겠습니다 .
>>> import os
>>> os.stat('c:/pagefile.sys').st_size==0
False
False
비어 있지 않은 파일을 의미합니다.
함수를 작성해 봅시다 :
import os
def file_is_empty(path):
return os.stat(path).st_size==0
답변
Python3을 사용하는 경우 속성 (파일 크기 (바이트)) 이있는 메소드를 사용하여 정보에 pathlib
액세스 할 수 있습니다 .os.stat()
Path.stat()
st_size
>>> from pathlib import Path
>>> mypath = Path("path/to/my/file")
>>> mypath.stat().st_size == 0 # True if empty
답변
파일 객체가 있다면
>>> import os
>>> with open('new_file.txt') as my_file:
... my_file.seek(0, os.SEEK_END) # go to end of file
... if my_file.tell(): # if current position is truish (i.e != 0)
... my_file.seek(0) # rewind the file for later use
... else:
... print "file is empty"
...
file is empty
