简体   繁体   English

pathlib 路径`write_text` 在追加模式

[英]pathlib Path `write_text` in append mode

Is there a shortcut for python pathlib.Path objects to write_text() in append mode?在追加模式下,python pathlib.Path对象是否有write_text()的快捷方式?

The standard open() function has mode="a" to open a file for writing and appending to the file if that file exists, and a Path s .open() function seems to have the same functionality ( my_path.open("a") ).标准的open()函数有mode="a"来打开一个文件,如果该文件存在,则用于写入和附加到文件中,并且Path s .open()函数似乎具有相同的功能( my_path.open("a") )。

But what about the handy .write_text('..') shortcut, is there a way to use pathlib to open and append to a file with just doing the same things as with open() ?但是方便的.write_text('..')快捷方式呢,有没有办法使用pathlib来打开pathlib加到文件中,而只需执行与open()相同的操作?

For clarity, I can do为了清楚起见,我可以做

with my_path.open('a') as fp:
    fp.write('my text')

but is there another way?但还有另一种方法吗?

my_path.write_text('my text', mode='a')

Not really, as you can see in the pathlib module exist 2 types of path classes:并非如此,正如您在 pathlib 模块中看到的那样,存在两种类型的路径类:

  • pure path classes {PurePath, PurePosixPath, PureWindowsPath}纯路径类{PurePath、PurePosixPath、PureWindowsPath}
  • concrete path classes {Path, PosixPath, WindowsPath}.具体路径类{Path, PosixPath, WindowsPath}。

Parameters of theses classes constructors will be just *pathsegments .这些类构造函数的参数将只是*pathsegments

And if you look at the available read/write methods (read_text/read_bytes and write_text/write_bytes) you'll also see mode won't be available neither如果您查看可用的读/写方法(read_text/read_bytes 和 write_text/write_bytes),您还会看到 mode 也不可用

So, as you've already discovered, the only way you can use mode with these pathlib classes is by using open method, ie:因此,正如您已经发现的那样,您可以对这些 pathlib 类使用 mode 的唯一方法是使用open方法,即:

with my_path.open("a") as f:
    f.write("...")

This is by design and that way the pathlib classes have become really "clean".这是设计使然,这样 pathlib 类就变得非常“干净”。 Also, the above snippet is already canonical so it can't be simplified any further.此外,上面的代码片段已经是规范的,因此无法进一步简化。 You could use open method outside the context manager though:不过,您可以在上下文管理器之外使用open方法:

f = my_path.open("a")
f.write("...")

In library pathlib, the method Path().write_text and Path().write_bytes close startment on finalize it.在库 pathlib 中,方法 Path().write_text 和 Path().write_bytes 在完成它时关闭开始。 ex:前任:

from pathlib import Path

Path('file.txt').write_text('my text')
Path('file1.txt').write_bytes(b'my text')

When use other mode on method, like append (a), the method open TextIOWrapper, and write_[text|bytes] close TextIOWrapper automatic.当在方法上使用其他模式时,如 append (a),该方法自动打开 TextIOWrapper,并 write_[text|bytes] 关闭 TextIOWrapper。

f = Path('file.txt')
f.open("a")
f.write_text('my text')

or或者

f = Path('file1.txt')
f.open("a")
f.write_bytes(b'my text')

Otherwise must close it manually否则必须手动关闭它

f = Path('file1.txt').open('a')
f.write('my text')
f.close()

but can be this way:但可以这样:

fp = Path('test.txt').open('a')
<_io.TextIOWrapper name='test.txt' mode='a' encoding='UTF-8'>
fp.write('my text')

fq = Path('test1.txt').open('ab', encoding='iso8859-1')
<_io.TextIOWrapper name='test1.txt' mode='a' encoding='iso8859-1'>
fq.write(b'my text')

If its just too much trouble to use the WITH structure, this might provide a sort of work around:如果使用 WITH 结构太麻烦,这可能会提供一种解决方法:

from pathlib import Path as p
t1 = "The quick brown fox" 
t2 = "just jumped over the fence"
t3 = "to greet the lazy poodle."
mypath = p("D:\Try_this")
myfile = p("fox.txt")
if not(mypath.is_dir()):
    mypath.mkdir()
wholepath = p(mypath / myfile)
wholepath.write_text("\n".join([t1,t2,t3]))

There is no "append mode" for write_text , nor is there a corresponding append_text method. write_text没有“追加模式”,也没有相应的append_text方法。 If you need it, you can write a function for it yourself pretty easily:如果你需要它,你可以很容易地自己为它编写一个函数:

def append_text(path, text, encoding=None, errors=None):
   with path.open("a", encoding=encoding, errors=errors) as f:
       f.write(text)

You might be wondering why such a thing isn't built directly into pathlib as a method.您可能想知道为什么不将这样的东西作为方法直接构建到pathlib中。 One reason is precisely because it is so easy to implement yourself that it's not really worth adding, but clearly that's not the whole story, because read_text and write_text would be similarly easy to implement yourself.一个原因正是因为它很容易实现你自己,所以它并不值得添加,但显然这不是全部,因为read_textwrite_text同样容易实现你自己。

I think a major reason why pathlib.Path objects don't (and, indeed, shouldn't) have a append_text method is because it creates a hole for inexperienced users to fall into, which is a huge sin in API design.我认为pathlib.Path对象没有(实际上,不应该)有append_text方法的一个append_text是因为它为没有经验的用户创造了一个漏洞,这是 API 设计中的一大罪过。

Specifically, the hole I'm referring to is using append_text on the same file repeatedly in a loop.具体来说,我所指的漏洞是在循环中重复在同一个文件上使用append_text Because you're continually opening and closing the file, it is slow .因为您不断地打开和关闭文件,所以速度 Plus, doing so many unnecessary writes is probably not great for the health of your hard drive.另外,进行这么多不必要的写入可能对硬盘驱动器的健康不利。

Worse, because the program will actually behave correctly (eg the file will have the contents they intended), they may not even notice anything is wrong, because they don't necessarily have a mental gauge on how long writing to a file "should" take.更糟糕的是,因为程序实际上会正确运行(例如,文件将包含他们想要的内容),他们甚至可能不会注意到任何错误,因为他们不一定有关于写入文件“应该”多长时间的心理衡量标准拿。

This is exactly the sort of code a naïve programmer would write:这正是一个天真的程序员会写的那种代码:

from pathlib import Path

N = 100

path = Path("numbers.txt")

path.write_text(f"{N}\n")
for i in range(N):
    path.append_text(f"{i}\n")
  • Is it a nice solution?这是一个很好的解决方案吗? No
  • Is it memory efficient?内存效率高吗? No
  • Is it a one-liner?是单线吗? Yes是的
from pathlib import Path

my_path = Path('/shopping_list.txt')

my_str = '\nFresh Spinach\nFrozen Strawberries'

my_str.write_text(my_path.read_text() + my_str)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM