Questa risposta è compatibile con tutte le versioni da Python-2.5 quando la parola chiave with
è stata rilasciata.
1. Crea il file se non esiste + Imposta l'ora corrente
(esattamente come il comando touch
)
import os
fname = 'directory/filename.txt'
with open(fname, 'a'): # Create file if does not exist
os.utime(fname, None) # Set access/modified times to now
# May raise OSError if file does not exist
Una versione più robusta:
import os
with open(fname, 'a'):
try: # Whatever if file was already existing
os.utime(fname, None) # => Set current time anyway
except OSError:
pass # File deleted between open() and os.utime() calls
2. Basta creare il file se non esiste
(non aggiorna l'ora)
with open(fname, 'a'): # Create file if does not exist
pass
3. Aggiorna semplicemente l'accesso al file / i tempi modificati
(non crea il file se non esistente)
import os
try:
os.utime(fname, None) # Set access/modified times to now
except OSError:
pass # File does not exist (or no permission)
L'uso os.path.exists()
non semplifica il codice:
from __future__ import (absolute_import, division, print_function)
import os
if os.path.exists(fname):
try:
os.utime(fname, None) # Set access/modified times to now
except OSError:
pass # File deleted between exists() and utime() calls
# (or no permission)
Bonus: tempo di aggiornamento di tutti i file in una directory
from __future__ import (absolute_import, division, print_function)
import os
number_of_files = 0
# Current directory which is "walked through"
# | Directories in root
# | | Files in root Working directory
# | | | |
for root, _, filenames in os.walk('.'):
for fname in filenames:
pathname = os.path.join(root, fname)
try:
os.utime(pathname, None) # Set access/modified times to now
number_of_files += 1
except OSError as why:
print('Cannot change time of %r because %r', pathname, why)
print('Changed time of %i files', number_of_files)