如何將 Python 的 itertools chain 寫入檔案裡?

時間 2021-05-07 21:01:42

1樓:

這樣就行了。你不能把乙個生成器write到檔案裡頭。

好歹先變成字串。

from itertools import chaina = "the quick brown fox jumps over the lazy dog.\n"

b = "do in rome as romans do.\n"

c = "where there is a will there is a way.\n"

with open("words.txt", "w") as f:

f.write(''.join(chain(a,b,c)))

2樓:

簡單回答是,引入迭代器並不會提高python寫檔案的效率。

題主的想法是引入乙個迭代器作為檔案的寫快取,其實這種快取系統已經提供。』print(text, flush=False)』。flush=False的含義是把字串放在快取裡,系統在未來同步快取。

flush=True強制系統完成快取同步之後才會執行下一條指令。python的print函式的預設引數flush=False,等於已經在讀寫時間加過一層快取了。

對於檔案IO的另一層優化,迭代器可以做到的是一次讀取一部分內容以節省空間。在迭代器裡檔案讀入並且建立引用是不可避免的。如果已經有額外的迭代器需要儲存的話,可以用map(f.

write, iterator)直接儲存。

如果內容需要從外部讀取的話,讀取步驟也可以省略。需要用到系統提供的流拷貝功能,在python裡的封裝是shutil.copyfileobj(src, des)。這裡寫乙個例子

from

shutil

import

copyfileobj

file1

=open

('file1.txt'

,'rb'

)file2

=open

('file2.txt'

,'rb'

)file3

=open

('file3.txt'

,'wb'

)file3

.write(b

'content in file 1:\n'

)copyfileobj

(file1

,file3

)file3

.write(b

'content in file 2:\n'

)copyfileobj

(file2

,file3

)file1

.close

()file2

.close

()file3

.close

()這裡官方文件顯示只能用在檔案描述符拷貝上,管道流的話python好像沒有提供特別好的拷貝辦法。multiprocess可以考慮重定向,sys.input的話可以當作迭代器讀取,不確定能不能用檔案描述符的方法拷貝。

3樓:Luyao Zou

額……王老師好像沒搞明白迭代器怎麼用。

迭代器裡的內容並不是直接用 print 或者 write 取出的。要用 for 語句或者 next() 方法。

你的例子裡面,可以這麼寫

with

open

("words.txt"

,"w")as

f:fort

intext:f

.write(t

)不過單純讀寫檔案的話,感覺不需要 itertools。檔案物件本身就是可迭代的。

with

open

("read.txt"

,'r')as

f,open

("write.txt"

,'w')as

g:fora_lineinf

:g.write

(a_line

)就可以把 read.txt 複製到 write.txt

如何將C 的API封裝成python可呼叫形式?

Menooker pybind11,繫結API形式借鑑了boost的python binding,但是不依賴boost。並且是header only,只要link python的lib就行 pybind11 Seamless operability between C 11 and Python 官...

Python如何將17 955四捨五入保留兩位小數?(直接用round結果不對)

工匠羅 import decimal def four down five up number decimal.getcontext rounding decimal.ROUND HALF UP b decimal.Decimal str number decimal.getcontextretur...

python如何將變數名轉化為同名字串?

在stack overflow 中看到過,唯一能解決的import inspect defretrieve name var Gets the name of var.Does it from the out most frame inner wards.param var variable to ...