Python 3.x Python3:尝试读取文件夹中的每个文件,并计算每个文件中的\n个数
长期搜索者,第一次呼叫者。我正试图为一位同事编写一些代码,以删除她的一些繁琐的复制和粘贴到excel中,从而计算每个.txt文件的行数。在第一个文件之后,我很难让我的代码在Pycharm中正确地重复每个文件 我的任务: 读取文件夹中的每个文件并返回每个文件的\n计数Python 3.x Python3:尝试读取文件夹中的每个文件,并计算每个文件中的\n个数,python-3.x,Python 3.x,长期搜索者,第一次呼叫者。我正试图为一位同事编写一些代码,以删除她的一些繁琐的复制和粘贴到excel中,从而计算每个.txt文件的行数。在第一个文件之后,我很难让我的代码在Pycharm中正确地重复每个文件 我的任务: 读取文件夹中的每个文件并返回每个文件的\n计数 for files in os.listdir(".."): if files.endswith(".txt"): print(files) lines = -1 try:
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))
所以这是一辆小马车。分层for循环不是我的强项,但我无法让它在读取第一个文件后返回下一个文件计数。谢谢。我想这就是你想要的
#!/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()
我只是四处寻找一些替代方法来计算文件中的行数,这就是我发现的。请让我们都知道它是否有效。在我的testdir-/home/user/projects/python/test/中有两个包含内容的文件
test1.txt
a
b
c
d
e
f
g
/home/user/projects/python/test/test1.txt has 4 lines inside.
/home/user/projects/python/test/test2.txt has 3 lines inside.
test2.txt
a
b
c
d
e
f
g
/home/user/projects/python/test/test1.txt has 4 lines inside.
/home/user/projects/python/test/test2.txt has 3 lines inside.
主代码
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))
输出
a
b
c
d
e
f
g
/home/user/projects/python/test/test1.txt has 4 lines inside.
/home/user/projects/python/test/test2.txt has 3 lines inside.
建议与open()一起使用-不需要closing语句,或者对每个打开的文件手动使用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)
对于f:中的行,第二个for循环应该是
,否则其他一切都应该正常工作。