Search code examples
pythonpython-3.xpycharmoperating-systemos.path

error getting was unix with os.path.getatime


I want to get the unix era of the file, but I get an error.

Code:

import os
from time import time
from datetime import datetime
import openpyxl


# Data do dia em unix.
data_hoje = time()

# Parâmetro de classificação em unix.
quinze_dias = 1296000
trinta_dias = 2592000
tres_meses = float(7776000)
seis_meses = 15552000

# Definição das pastas de trabalho.
main_path = r'C:\Users\eduar\Documents'

book = openpyxl.Workbook()

book.create_sheet('Dados')
frutas_page = book['Dados']
frutas_page.append(['Nome', 'Último acesso', 'Última modificação', 'Tamanho'])

for root, subfolder, filenames in os.walk(main_path):
    for file in filenames:
        unix_arquivo = os.path.getatime(file)
        if data_hoje - unix_arquivo >= tres_meses:
            nome = os.path.basename(file)
            acesso = datetime.utcfromtimestamp(os.path.getatime(file)).strftime('%Y-%m-%d')
            modificacao = datetime.utcfromtimestamp(os.path.getmtime(file)).strftime('%Y-%m-%d')
            frutas_page.append([nome, acesso, modificacao])

book.save('S:/Teste.xlsx')

error:

Traceback (most recent call last):
  File "S:\Documentos\ELO\main.py", line 27, in <module>
    unix_arquivo = os.path.getatime(file)
  File "S:\Python\3.9.7\lib\genericpath.py", line 60, in getatime
    return os.stat(filename).st_atime
FileNotFoundError: [WinError 2] O sistema não pode encontrar o arquivo especificado: 'adxregistrator.log'

The error is happening right at the time of getting the unix era of file access.


Solution

  • "FileNotFoundError" is the give-away. That means that the file you pass to getatime cannot be found. file is returned by os.walk, so you can be pretty sure it does actually exist, so why can't it be found? Because you need to provide the path to the file, and os.walk only returns the filename.

    Try this instead:

    import os
    
    for root, subfolder, filenames in os.walk("/var/tmp/"):
        for file in filenames:
            unix_arquivo = os.path.getatime(os.path.join(root, file))
            print("file: " + file + ". atime: " + str(unix_arquivo))
    

    Note that even still, you may get "FileNotFoundError" for some files. For example, symbolic links may need special handling.