读取文件而不截断,如果文件不存在,则创建文件

问题描述 投票:-1回答:1

我想从一个文件中读取数据而不截断它.我知道我可以使用'r'来读取。

但我也想在FileNotFoundError出现时创建文件。

但使用'w'、'w+'、'a+'来创建文件是可行的,但在以后的运行中,它也会截断文件中的任何现有数据。

基本上是在找一个替代品。

try:
    with open('filename', 'r') as file:
        #if no error is raised, file already exits and
        #can be read from: do stuff on file.
except FileNotFoundError:    
    with open('filename', 'x') as file:
        pass
        #no further actions are required here as the file 
        #is just being created

答案是:

打开文件进行随机写入而不截断?

说明我应该用'rb+'模式打开文件,然而'rb+'会引发FileNotFoundError,如果文件不存在,就不会创建文件。

以二进制模式打开文件也不适合读取文本文件。

python
1个回答
0
投票

你可以试试这样的方法。

>>> try:
...   t = open('filename', 'r+')
... except FileNotFoundError:
...   t = open('filename', 'x')
...
>>> with t as file:
...   file.write("Testing:\n")
...
9

赋值 open() 的名称,然后将该名称用在 with 语句也可以


1
投票

你可以用 os.path.exists() 替换使用 FileNotFoundError.

import os


path = '/tmp/test.info'

if os.path.exists(path):
    with open(path, 'r') as infile:
        print(infile.read())
else:
    open(path, 'x')

你也可以把所有的 os 用法 pathlib 如果你使用的是 Python 3.4+。

from pathlib import Path


path = Path('/tmp/test.info')

if path.is_file():
    print(path.read_text())
else:
    path.touch()

不过我并不确定这两种方式是否有什么改进。如果你想要简洁的话,这些可以减少到一行或两行,但它们的可读性会降低,而且仍然不是单个命令。

© www.soinside.com 2019 - 2024. All rights reserved.