相关疑难解决方法(0)

python open内置函数:模式a,a +,w,w +和r +之间的区别?

在内置的蟒蛇开放的功能,是个什么模式之间准确的区别w,a,w+,a+,和r+

特别是,文档暗示所有这些都允许写入文件,并说它打开文件"具体"附加",写入"和"更新",但没有定义这些术语的含义.

python

555
推荐指数
8
解决办法
36万
查看次数

如何打开(读写)或创建允许截断的文件?

我想要:

  • 以读写模式打开文件(如果存在);
  • 如果它不存在就创建它;
  • 能够随时随地截断它.

编辑:使用truncate我的意思是写入一个位置并丢弃文件的剩余部分(如果存在)

所有这些原子(通过单个open()调用或模拟单个open()调用)

似乎没有单一的开放模态适用:

  • r:显然不起作用;
  • r +:如果文件不存在则失败;
  • w:重新创建文件(如果存在);
  • w +:如果存在则重新创建文件;
  • a:看不懂;
  • a +:不能截断.

我试过的一些组合(rw,rw +,r + w等)似乎也不起作用.可能吗?

来自Ruby的一些文档(也适用于python):

r
Read-only mode. The file pointer is placed at the beginning of the file.
This is the default mode.

r+
Read-write mode. The file pointer will be at the beginning of the file.

w
Write-only mode. Overwrites the file if the file exists. If the file
does not exist, creates a new …
Run Code Online (Sandbox Code Playgroud)

ruby python truncate

36
推荐指数
2
解决办法
4万
查看次数

在Python中一次打开几次文件是否安全?

我似乎回想起低级语言中的情况,即在程序中多次打开文件可能会导致共享的搜索指针.通过在Python中乱搞一下,这似乎并没有发生在我身上:

$ cat file.txt
first line!
second
third
fourth
and fifth
Run Code Online (Sandbox Code Playgroud)
>>> f1 = open('file.txt')
>>> f2 = open('file.txt')
>>> f1.readline()
'first line!\n'
>>> f2.read()
'first line!\nsecond\nthird\nfourth\nand fifth\n'
>>> f1.readline()
'second\n'
>>> f2.read()
''
>>> f2.seek(0)
>>> f1.readline()
'third\n'
Run Code Online (Sandbox Code Playgroud)

这种行为是否安全?我很难找到一个消息来源说它没关系,如果我可以依赖它,它会有很大帮助.

我没有将该位置视为文件对象的属性,否则我对此更有信心.我知道它可以保存在迭代器内部,但idk如何.tell()在这种情况下会得到它.

>>> dir(f1)
['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__',
 '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
 '__setattr__', '__str__', 'close', 'closed', 'encoding', 'fileno', 'flush',
 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline',
 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines',
 'xreadlines']
Run Code Online (Sandbox Code Playgroud)

更新
Python基本参考的 …

python file seek

17
推荐指数
1
解决办法
9192
查看次数

如何一次读取和附加到文本文件?

我想检查一个字符串是否在文本文件中,然后附加该字符串,如果它不存在.

我知道我可以通过创建两个单独的with方法来实现这一点,一个用于读取,另一个用于追加,但是是否可以在同一个with方法中读取和追加?

我想出的最接近的是:

with open("file.txt","r+") as file:
    content=file.read()
    print("aaa" in content)
    file.seek(len(content))
    file.write("\nccccc")
Run Code Online (Sandbox Code Playgroud)

我的file.txt:

aaaaa
bbbbb
Run Code Online (Sandbox Code Playgroud)

当我第一次运行代码时,我得到了这个:

aaaaa
bbbbb
ccccc
Run Code Online (Sandbox Code Playgroud)

但是,如果我再次运行它,这会出现:

aaaaa
bbbbb
ccc
ccccc
Run Code Online (Sandbox Code Playgroud)

我希望第三行是ccccc.

任何人都可以解释为什么在第二次运行中截断最后两个字符?另外,如何读取文本并将其附加到文件中?

python file file-read file-writing

3
推荐指数
1
解决办法
4990
查看次数

标签 统计

python ×4

file ×2

file-read ×1

file-writing ×1

ruby ×1

seek ×1

truncate ×1