gpt4 book ai didi

python - 查找文件夹内所有文件的行数

转载 作者:行者123 更新时间:2023-12-02 02:21:16 24 4
gpt4 key购买 nike

您好,我正在尝试查找文件夹中所有文件的行数。我正在尝试对仅包含“.txt”文件的文件夹和包含“csv”文件的文件夹执行此操作。

我知道获取单个“.txt”文件行数的方法如下:

file = open("sample.txt","r") 
Counter = 0

Content = file.read()
CoList = Content.split("\n")

for i in CoList:
if i:
Counter += 1

print("This is the number of lines in the file")
print(Counter)

对于单个“.csv”文件来说,是这样的:

file = open("sample.csv")
reader = csv.reader(file)
lines= len(list(reader))
print(lines)

但是如何对文件夹中的所有文件执行此操作?也就是说,我如何在文件夹内的所有文件中循环每个过程,并且理想情况下,将输出导出到包含类似于以下列的 Excel 工作表中:

Filename  Number of Rows
1.txt 900
2.txt 653

等等等等。

非常感谢您的帮助。

最佳答案

您可以使用 glob 来检测文件,然后迭代它们。

其他方法:How do I list all files of a directory?

import glob

# 1. list all text files in the directory
rel_filepaths = glob.glob("*.txt")

# 2. (optional) create a function to read the number of rows in a file
def count_rows(filepath):
res = 0
f = open(filepath, 'r')
res = len(f.readlines())
f.close()

return res

# 3. iterate over your files and use the count_row function
counts = [count_rows(filepath) for filepath in rel_filepaths]

print(counts)

然后,如果您想将此结果导出到 .csv.xslx 文件中,我建议使用 pandas

import pandas as pd

# 1. create a new table and add your two columns filled with the previous values
df = pd.DataFrame()
df["Filename"] = rel_filepaths
df["Number of rows"] = counts

# 2. export this dataframe to `.csv`
df.to_csv("results.csv")

如果您想使用.xlsx 格式,也可以使用pandas.ExcelWriter()。文档和示例链接:Pandas - ExcelWriter doc

关于python - 查找文件夹内所有文件的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66388995/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com