Python3:尝试读取文件夹中的每个文件,并计算每个文件中有多少\ n

时间:2017-07-10 21:19:13

标签: python-3.x

长时间的搜索者,第一次来电。我试图为同事编写一些代码,以删除她的一些繁琐的副本。粘贴到Excel中以计算每个.txt文件的行数。在第一个文件之后,我在Pycharm中为每个文件正确地重复我的代码时遇到了一些麻烦。

我的任务: 读取文件夹中的每个文件,并为每个文件返回\ 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))

所以它有点小马车。分层循环不是我的强项,但我无法让它在读取第一个文件后返回下一个文件计数。感谢。

2 个答案:

答案 0 :(得分:1)

在我的testdir中 - / home / user / projects / python / test / 包含2个包含内容的文件。

<强> test1.txt的

AttributeError: 'str' Object has no attribute 'extend'

<强>的test2.txt

a
b
c
d

主要代码

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))

建议使用open() - 不需要关闭语句,或者对每个打开的文件手动使用f.close()。换句话说,在你的行+ = 1之后添加f.close(),并使用与f.open()相同的缩进。

检查* .txt文件是否存在比检查文件是否可以打开更重要。

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

答案 1 :(得分: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()

我只是寻找一些替代方法来计算文件中的行数,这就是我发现的。如果有效,请告诉我们。