最新消息:20210917 已从crifan.com换到crifan.org

【已解决】Python中实现类似touch创建一个空文件

Python crifan 750浏览 0评论
折腾:
【未解决】mac中如何获取electron的app的根目录
期间,想要Python实现类似于touch一样,创建一个空文件。
python create empty file
Create empty file using python – Stack Overflow
how to create empty file in python – Stack Overflow
How to empty a file using Python – Stack Overflow
python – creating an empty file and closing in one line – Stack Overflow
【总结】
代码:
def createEmptyFile(fullFilename):
    """Create a empty file like touch"""
    filePath = os.path.dirname(fullFilename)
    # create folder if not exist
    if not os.path.exists(filePath):
        os.makedirs(filePath)


    with open(fullFilename, 'a'):
        # Note: not use 'w' for maybe conflict for others constantly writing to it
        os.utime(fullFilename, None)
后续看到:
utility – Implement touch using Python? – Stack Overflow
对于 Python 3.4+ ,最好用:
from pathlib import Path
Path(fullFilename).touch()
调用:
createEmptyFile(self.fileToSave)
效果:
【后记20201027】
更新注释:
def createEmptyFile(fullFilePath):
    """Create a empty file like touch


    Args:
        fullFilePath (str): full file path
    Returns:
        bool
    Raises:
    """
    folderPath = os.path.dirname(fullFilePath)
    # create folder if not exist
    if not os.path.exists(folderPath):
        os.makedirs(folderPath)


    with open(fullFilePath, 'a'):
        # Note: not use 'w' for maybe conflict for others constantly writing to it
        os.utime(fullFilePath, None)
最新代码:
https://github.com/crifan/crifanLibPython/blob/master/crifanLib/crifanFile.py

转载请注明:在路上 » 【已解决】Python中实现类似touch创建一个空文件

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
85 queries in 0.212 seconds, using 20.15MB memory