2017-07-10 36 views
1

長時間搜索器,第一次調用者。我正在嘗試爲同事編寫一些代碼,以刪除她的一些繁瑣副本&,粘貼到excel中以計算每個.txt文件的行數。我遇到了一些麻煩,讓我的代碼在第一次之後在每個文件的Pycharm中正確重複。Python3:嘗試讀取文件夾中的每個文件,並計算每個文件中有多少個 n

我的任務: 讀取文件夾中的每個文件,併爲每個文件返回一個\ n數。

for files in os.listdir(".."): 
    if files.endswith(".txt"): 
     print(files) 
     lines = -1 
     try: 
      f = open(files,"r") 
      for line in files: 
       lines += 1 
     except: 
      print("problem") 
     print('%r has %r lines inside' % (files, lines)) 

所以這是一個小錯誤。爲循環分層並不是我的強項,但是在讀取第一個文件之後,我無法讓它返回下一個文件數。謝謝。

+1

你的第二個for循環應該是'for line in f:',否則其他的一切都應該工作。 – victor

回答

1

在我的testdir裏面 - /home/user/projects/python/test/有2個文件的內容。

test1.txt的

a 
b 
c 
d 

的test2.txt

e 
f 
g 

主代碼

import os 

testdir = '/home/user/projects/python/test' 

for file in os.listdir (testdir): 
    lc = 0  # line count - reset to zero for each file 
    if file.endswith ('.txt'): 
     filename = '%s/%s' % (testdir, file) # join 2 strings to get full path 
     try: 
      with open (filename) as f: 
       for line in f: 
        lc += 1 
     except: 
      print ('Problem!') 
    print ('%s has %s lines inside.' % (filename, lc)) 

輸出

/home/user/projects/python/test/test1.txt has 4 lines inside. 
/home/user/projects/python/test/test2.txt has 3 lines inside. 

建議用open()來使用 - 無需閉幕詞或手動使用f.close(),每個打開的文件。換句話說,在你的行+ = 1之後加上f.close(),它的縮進與f.open()相同。

也許檢查* .txt文件是否存在比檢查文件是否可以打開更重要。

for file in os.listdir (testdir): 
    lc = 0 
    filename = '%s/%s' % (testdir, file) 
    if file.endswith ('.txt') and os.path.isfile (filename): 
     with open (filename) as f: 
      for line in f: 
       lc += 1 
     print ('%s has %s lines inside.' % (filename, lc)) 
    else: 
     print ('No such file - %s' % filename) 
0

我認爲這是你想要的。

#!/usr/bin/python3 
import os 

def main(): 

    for files in os.listdir("PATH TO FOLDER CONTAINING THIS SCRIPT + TEXT FILES"): 
     if files.endswith(".txt"): 
      print(files) 

      num_lines = sum(1 for line in open(files)) 

      print("problem") 
      print('%r has %r lines inside' % (files, num_lines)) 

if __name__ == "__main__": main() 

我剛剛搜尋了一些替代方法來計算文件中的行,這就是我發現的。請讓我們都知道它是否有效。

相關問題