[英]Why does my if condition in my for loop stop validation after one iteration is true?
[英]Why does my loop stop after one iteration?
我正在努力查看為什么我的循環在一次迭代后停止。
我的代碼:
import os
def open_data(fpath):
counter=0
for i in os.listdir(fpath):
if os.path.isfile(os.path.join(fpath,i)):
#print counter
f=open(os.path.join(fpath,i),"r")
#counter=counter+1
return counter,f.readlines()
#f.close()
x=open_data("C:/Users/manchester/.ipynb_checkpoints/txt_sentoken/practice_")
基本上,我試圖遍歷目錄中包含電影評論的所有文件。 我的首要目標是使用一個函數從目錄中讀取所有文件,然后我需要說70%的評論用於培訓10%的測試,10%的驗證,10%的超參數采樣。 但是我無法克服嘗試使用函數讀取所有文件的第一個障礙。
我已經嘗試使用列表和追加,但這也不起作用。
你是不是讀你只打開了所有的文件,在相同的變量,並在結束的時候,你正在做的文件f.readlines()
f
這只是什么是你的最后一個文件,你應該閱讀所有的“緩沖”最后返回
應該是這樣的
def open_data(fpath):
counter=0
all_lines = []
for i in os.listdir(fpath):
if os.path.isfile(os.path.join(fpath,i)):
all_lines += open(os.path.join(fpath,i),"r").readlines()
counter=counter+1
return counter,all_lines
請記住,讀取很多最終的大文件會增加內存,如果您的代碼允許,最好使用生成器
def get_lines(fpath):
for i in os.listdir(fpath):
if os.path.isfile(os.path.join(fpath,i)):
for line in open(os.path.join(fpath,i),"r"):
yield line
# this would give you an iterable over all the lines in all the files, one line at a time
稍后編輯:我有一個文件夾“ x”,其中包含2個文件“ f1”和“ f2”; “ f1”包含數字1,2,3每行一個,而“ f2”包含數字4,5,6
>>> print open_data(".\\x") # gives
(2, ['1\n', '2\n', '3\n', '4\n', '5\n', '6\n'])
使用生成器,您將沒有所有行的列表,但是有一個“可迭代”,可以將其稱為“惰性閱讀器”,要使用它,您必須對其進行迭代
>>> for line in get_lines(".\\x"):
... print line # will give
1
2
3
4
5
6
數字之間的額外行是\\n
沿着打印的文件中讀取\\n
打印添加
這樣,代碼將只返回目錄的最后一個文件。
您沒有對打開的文件執行任何操作,然后返回最后一個文件。
我猜您應該將f.readlines
附加在列表中,然后在函數末尾返回列表。
但是計數器應該可以工作,返回目錄中的文件數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.