[英]How to iterate in a file inside a function in Python3?
我有這個功能,可以打開兩個文件,一個用於讀取,一個用於寫入。 我遍歷input_file
並將其中的一些項目寫入save_file
。
with open(input_file, 'r') as source, open(save_file, 'w') as dest:
reader = csv.reader(source)
writer = csv.writer(dest)
for row in reader:
#do_something
find_min(save_file, threshold)
雖然通過迭代我想調用另一個函數並遍歷我附加在save_file
上的save_file
,但是當我調用它並嘗試打印它們時,沒有打印任何內容。
這是我調用的函數:
def find_min(file, threshold):
with open(file, 'r') as f:
reader = csv.reader(f)
for i in reader:
print(i)
如果我嘗試在with
語句之外調用find_min
函數,則文件將正常迭代並打印出來。
但是我想多次調用這個函數來分析和壓縮初始數據。
因此,沒有人知道如何通過迭代save_file
在find_min
功能。
問題是您沒有關閉輸出文件(或將其內容刷新到磁盤),因此在關閉之前無法可靠地讀取它。 解決方案是使用標志w+
打開文件進行讀寫:
with open(input_file, 'r') as source, open(save_file, 'w+') as dest:
然后傳遞給find_min
dest
:
find_min(dest, threshold)
# make sure we are once again positioned at the end of file:
# probably not necessary since find_min reads the entire file
# dest.seek(0, 2)
def find_min(dest, threshold):
dest.seek(0, 0) # seek to start of file for reading
reader = csv.reader(dest)
for i in reader:
print(i)
# we should be back at end of file for writing, but if we weren't, then: dest.seek(0, 2)
如果find_min
沒有通過不讀取整個文件find_min
dest
位於文件末尾,則必須在恢復寫入之前調用dest.seek(0, 2)
以確保我們首先位於文件末尾.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.