Bu yanıt, anahtar kelime with
serbest bırakıldığında Python-2.5'ten beri tüm sürümlerle uyumludur .
1. Varsa dosya oluştur + Geçerli saati ayarla
(komutla tamamen aynı 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
Daha sağlam bir sürüm:
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. Sadece yoksa dosyayı oluşturun
(zamanı güncellemez)
with open(fname, 'a'): # Create file if does not exist
pass
3. Sadece dosya erişimini / değiştirilen süreleri güncelleyin
(mevcut değilse dosya oluşturmaz)
import os
try:
os.utime(fname, None) # Set access/modified times to now
except OSError:
pass # File does not exist (or no permission)
Kullanmak os.path.exists()
kodu basitleştirmez:
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: Bir dizindeki tüm dosyaların süresini güncelleme
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)