Python을 사용하여 touch를 구현하시겠습니까?
touch
는, 파일의 변경과 액세스 시간을 현재의 시각으로 설정하는 Unix 유틸리티입니다.파일이 존재하지 않으면 기본 권한으로 생성됩니다.
Python 함수로 어떻게 구현하시겠습니까?크로스 플랫폼이 되어 완전해지도록 노력하세요.
("python touch file"에 대한 Google의 현재 결과는 그다지 좋지 않지만 os.utime을 가리키고 있습니다.)
이것은 Python 3.4부터 새로운 것 같습니다.
from pathlib import Path
Path('path/to/file.txt').touch()
이렇게 하면file.txt
길목에서.
--
Path.touch(모드=0o777, exist_ok=True)
이 지정된 경로에 파일을 만듭니다.모드를 지정하면 프로세스의 umask 값과 결합하여 파일 모드 및 액세스 플래그를 결정합니다.파일이 이미 존재하는 경우 exist_ok가 true이면 함수가 성공하고(수정 시간이 현재 시간으로 업데이트됨), 그렇지 않으면 FileExistsError가 발생합니다.
이것은 다른 솔루션보다 조금 더 인종을 배제하려고 합니다.(the.with
키워드는 Python 2.5에서는 새로운 것입니다.)
import os
def touch(fname, times=None):
with open(fname, 'a'):
os.utime(fname, times)
대략 이것과 같다.
import os
def touch(fname, times=None):
fhandle = open(fname, 'a')
try:
os.utime(fname, times)
finally:
fhandle.close()
레이스 프리하게 하려면 , 파일을 열어 파일명의 타임스탬프를 변경하는 대신에, 열려 있는 파일 핸들의 타임스탬프를 사용해 변경할 필요가 있습니다(이름 변경되었을 가능성이 있습니다).안타깝게도 Python은 전화할 방법을 제공하지 않는 것 같습니다.futimes
통과하지 않고ctypes
또는 비슷한...
편집
Nate Parsons가 지적한 바와 같이, Python 3.3은 파일 기술자(시기)를 지정하는 기능을 추가합니다.futimes
syscall 대신utimes
보닛 밑에 시스콜.즉, 다음과 같습니다.
import os
def touch(fname, mode=0o666, dir_fd=None, **kwargs):
flags = os.O_CREAT | os.O_APPEND
with os.fdopen(os.open(fname, flags=flags, mode=mode, dir_fd=dir_fd)) as f:
os.utime(f.fileno() if os.utime in os.supports_fd else fname,
dir_fd=None if os.supports_fd else dir_fd, **kwargs)
def touch(fname):
if os.path.exists(fname):
os.utime(fname, None)
else:
open(fname, 'a').close()
이것을 사용해 보는 것은 어떨까요?
import os
def touch(fname):
try:
os.utime(fname, None)
except OSError:
open(fname, 'a').close()
나는 이것이 중요한 경주 조건을 제거한다고 믿는다.파일이 존재하지 않으면 예외가 느려집니다.
여기서 생각할 수 있는 유일한 레이스 조건은 open()이 호출되기 전에 파일이 작성되었지만 os.utime()이 호출된 후에 작성되었을 경우입니다.다만, 이 경우는, 변경 시간이 예상대로 되기 때문에, 이것은 문제가 되지 않습니다.이는 Touch()에의 콜중에 발생한 것이 틀림없기 때문입니다.
이 답변은 키워드가 출시된 Python-2.5 이후의 모든 버전과 호환됩니다.
1. 없는 경우 파일 생성 + 현재 시간 설정
(명령어와 동일)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
보다 견고한 버전:
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 . 존재하지 않는 경우 파일을 만듭니다.
하지 않음) ('시간 갱신')
with open(fname, 'a'): # Create file if does not exist
pass
3.된 시간만 .3 . ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
하지 않는 경우 하지 않음)('파일 작성')
import os
try:
os.utime(fname, None) # Set access/modified times to now
except OSError:
pass # File does not exist (or no permission)
「」를 사용합니다.os.path.exists()
는 .
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)
보너스: 디렉토리에 있는 모든 파일의 업데이트 시간
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)
보다 낮은 수준의 솔루션에는
os.close(os.open("file.txt", os.O_CREAT))
다음은 ctype을 사용하는 코드입니다(Linux에서만 테스트됨).
from ctypes import *
libc = CDLL("libc.so.6")
# struct timespec {
# time_t tv_sec; /* seconds */
# long tv_nsec; /* nanoseconds */
# };
# int futimens(int fd, const struct timespec times[2]);
class c_timespec(Structure):
_fields_ = [('tv_sec', c_long), ('tv_nsec', c_long)]
class c_utimbuf(Structure):
_fields_ = [('atime', c_timespec), ('mtime', c_timespec)]
utimens = CFUNCTYPE(c_int, c_char_p, POINTER(c_utimbuf))
futimens = CFUNCTYPE(c_int, c_char_p, POINTER(c_utimbuf))
# from /usr/include/i386-linux-gnu/bits/stat.h
UTIME_NOW = ((1l << 30) - 1l)
UTIME_OMIT = ((1l << 30) - 2l)
now = c_timespec(0,UTIME_NOW)
omit = c_timespec(0,UTIME_OMIT)
# wrappers
def update_atime(fileno):
assert(isinstance(fileno, int))
libc.futimens(fileno, byref(c_utimbuf(now, omit)))
def update_mtime(fileno):
assert(isinstance(fileno, int))
libc.futimens(fileno, byref(c_utimbuf(omit, now)))
# usage example:
#
# f = open("/tmp/test")
# update_mtime(f.fileno())
심플화:
def touch(fname):
open(fname, 'a').close()
os.utime(fname, None)
open
이 있는지 합니다.utime
.
open
이로 인해 utime이 예외를 발생시킵니다.하지만, 나쁜 일이 일어났기 때문에 괜찮습니다.하지만 분명 그건 괜찮아, 뭔가 안 좋은 일이 일어났으니까.
with open(file_name,'a') as f:
pass
다음 사항으로 충분합니다.
import os
def func(filename):
if os.path.exists(filename):
os.utime(filename)
else:
with open(filename,'a') as f:
pass
특정 터치 시간을 설정하려면 다음과 같이 os.utime을 사용합니다.
os.utime(filename,(atime,mtime))
여기서 atime과 mtime은 모두 int/float이어야 하며 설정하는 시간의 초단위와 같아야 합니다.
복잡함(버그가 있을 수 있음):
def utime(fname, atime=None, mtime=None)
if type(atime) is tuple:
atime, mtime = atime
if atime is None or mtime is None:
statinfo = os.stat(fname)
if atime is None:
atime = statinfo.st_atime
if mtime is None:
mtime = statinfo.st_mtime
os.utime(fname, (atime, mtime))
def touch(fname, atime=None, mtime=None):
if type(atime) is tuple:
atime, mtime = atime
open(fname, 'a').close()
utime(fname, atime, mtime)
이것은 GNU touch와 같이 액세스 시간이나 수정 시간을 설정할 수도 있습니다.
원하는 변수를 사용하여 문자열을 생성하여 os.system에 전달하는 것이 논리적으로 보일 수 있습니다.
touch = 'touch ' + dir + '/' + fileName
os.system(touch)
이것은 여러 가지 면에서 불충분하므로(예: 공백 공간을 처리하지 않음) 하지 마십시오.
보다 견고한 방법은 다음과 같은 서브프로세스를 사용하는 것입니다.
subprocess.call(['touch', os.path.join(dirname, fileName)])
(OS.system에서) 서브셸을 사용하는 것보다 훨씬 낫지만, 여전히 빠른 더티 스크립트에만 적합합니다. 크로스 플랫폼 프로그램에 대해서는 승인된 답변을 사용하십시오.
write_text()
부에서pathlib.Path
사용할 수 있다.사용할 수 있습니다.
>>> from pathlib import Path
>>> Path('aa.txt').write_text("")
0
new file을 사용해 보는 것은 어떨까요?화이
#!/usr/bin/env python
import sys
inputfile = sys.argv[1]
with open(inputfile, 'r+') as file:
pass
python newfile.py foobar.txt
또는
하위 프로세스 사용:
import subprocess
subprocess.call(["touch", "barfoo.txt"])
터치용 파이썬 모듈도 있습니다.
>>> from touch import touch
>>> touch(file_name)
You can install it with 를 사용하여 설치할 수 있습니다.pip install touch
언급URL : https://stackoverflow.com/questions/1158076/implement-touch-using-python
'IT' 카테고리의 다른 글
Java의 if 문의 긴 목록 (0) | 2022.12.27 |
---|---|
SQL: 프리픽스가 있는 테이블 삭제 (0) | 2022.12.27 |
할당 후 예기치 않게 변경되지 않도록 목록을 복제하려면 어떻게 해야 합니까? (0) | 2022.12.27 |
JavaScript 파일 업로드 크기 확인 (0) | 2022.12.27 |
navigator.geolocation.getCurrentPosition이 작동하지 않을 수 있음 (0) | 2022.12.27 |