-4

感谢您在星期五的所有帮助。对不起,也许我的简单问题。由于我是 Python 的初学者,有时我会遇到一些对于更专业的人来说很容易的问题,但我会努力提高自己。

我将更详细地澄清我之前的问题。我有一些文本文件,在您的指导下,我可以数出这些文本文件的行数。我想创建一个新的文本文件作为输出,在这个新文件的每一行中,我都有输入文件的名称以及带空格的行数,并且该文件的最后一行包含行号的总和. 例如,我有一些文件:points1.txt、points2.txt 和 points3.txt。输出文件为:

点1 144798 点2 100000 点3 258627 总和 503425

我的代码是:

导入操作系统文件夹 = 'E:/MLS_HFT/TEST/Stuttgart_2009_pointclouds/'

def total_lines():

    count_line = 0

    for filename in os.listdir(folder):
        infilename = os.path.join(folder,filename)
        if not os.path.isfile(infilename): continue
        infile= open(infilename, 'r')

        for lines in infile:
            i+=1

        outfile = ["%s " %i]
        return i
        outfile = ["%s " %i]
        outfile.write("\n".join(output))
        outfile.close()
        return outfile

        total_lines (infile,i)
        count_line = count_line + i

        output = ["%s  %s" %(item.strip() ,count_line) for item in outfile]
    outfile.write("\n".join(output))

我很感谢您的指导。

4

4 回答 4

2

如果您只想要每个文件中行数的总数:

>>> import fileinput
>>> i = 0 # default value 
>>> for line in fileinput.input(files=('test.txt', 'test2.txt')):
        i += 1


>>> i
20

这可以简化为:

sum(1 for line in fileinput.input(files=('test.txt', 'test2.txt'))

如果您想要单个文件,并且还必须将它们相加,只需在函数中使用它:

with open('test.txt') as f:
    sum(1 for line in f)
于 2013-04-19T10:27:51.680 回答
1

要获取文件中的行数,请打开它并读取如下行:

fid = open('your input filename', 'r')
lines = fid.readlines()
nLines = len(lines)

然后,您可以将上述内容放在一个循环中,打开每个文件并将所有 nLines 值相加以计算总数。

编辑:

像这样循环文件:

infiles = ['file1.txt', 'file2.txt', 'file3.txt', ... , 'fileN.txt' ]
totalLines = 0

# Loop over array of files
for filename in infiles:
    # Open file:
    fid = open(filename, 'r')

    # Read lines and get length of returned array (array of lines):
    lines = fid.readlines()
    nLines = len(lines)
    totalLines += nLines   # Sum with total lines

    # Close the file
    fid.close()

# Show total:
print "Total lines from all files: " + totalLines
于 2013-04-19T10:30:00.237 回答
0

假设您的文件结构如下,并且每个文件中的标题是“点”

file1.txt     file2.txt    file3.txt

points        points       points
23            43           12
34            32           45
45            21           99
56                         100
                           123

代码如下:

import pandas as pd # pandas is powerful
import glob # finds all the pathnames matching a specified pattern 
import os
file_count_and_sum = []
os.chdir("E:/Pointfiles") # the folder where your text files are
for file in glob.glob("*.txt"):
    data = pd.read_csv(file)
    file_count_and_sum.append([file,len(data['points'].values),sum(data['points'].value        s)])
print file_count_and_sum 

您的输出将像这样打印文件名、计数和总和;

[['file1.txt', 4, 158], ['file2.txt', 3, 96], ['file3.txt', 5, 379]]

编辑:在那种情况下,这行得通吗?

count = 0  
for file in glob.glob("*.txt"):
   data = pd.read_csv(file)
   count = count + len(data['points'].values)
print count
于 2013-04-19T10:50:04.907 回答
0
def Total_Lines():    
    Open_File = open(File_Name,'U').read()
    Last_Line = Open_File.count('\n')
    print Last_Line

计算文件中的行数

对于多个文件

import glob

def Total_Lines(path):
    Count_Line = 0
    a = glob.glob(path+'\*')
    for i in a:
        print i
        Open_File = open(i,'U').read()
        Last_Line = Open_File.count('\n')
        print Last_Line
        Count_Line = Count_Line+Last_Line
    print Count_Line

Total_Lines(r"F:\stack")
于 2013-04-19T10:27:00.283 回答