Home > Article > Backend Development > 如何利用python读取特定目录下的特定文件的倒数两行?
本人刚接触python,在书上看到一个习题,问题如下:
1、列出指定目录”c:\”所有的后缀名为*.txt 的文件(包括子文件夹内所有文件),并输出每个文件的创建日期和大小
2、针对上述文件,取内容倒数 2 行,存入新文件,取名“list.txt”
3、将上述文件按照创建时间进行正向排序(从小到大),存入新文件,取名“排序.txt”
我尝试做了一下,但是有几个地方总是做到一半就没思路了,求助各位!
<span class="kn">import</span> <span class="nn">os</span> <span class="k">for</span> <span class="n">parent</span><span class="p">,</span><span class="n">dirnames</span><span class="p">,</span><span class="n">filenames</span> <span class="ow">in</span> <span class="n">os</span><span class="o">.</span><span class="n">walk</span><span class="p">(</span><span class="s">'C:'</span><span class="p">):</span> <span class="c">#遍历C:下的文件 </span> <span class="k">for</span> <span class="n">filename</span> <span class="ow">in</span> <span class="n">filenames</span><span class="p">:</span> <span class="c">#循环文件列表 </span> <span class="k">if</span> <span class="s">".txt"</span> <span class="ow">in</span> <span class="n">filename</span><span class="p">:</span> <span class="c">#找出所以后缀是.txt的文件 </span> <span class="n">myfile</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">parent</span><span class="p">,</span><span class="n">filename</span><span class="p">))</span> <span class="c">#得到该文件的绝对路径并打开文件 </span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">myfile</span><span class="o">.</span><span class="n">readlines</span><span class="p">():</span> <span class="c">#读取文件每一行,并循环 </span> <span class="nb">open</span><span class="p">(</span><span class="s">'./list.txt'</span><span class="p">,</span><span class="s">'a'</span><span class="p">)</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">line</span><span class="p">)</span> <span class="c">#将该行写入指定名称为'list.txt'的文件中去</span>
这个实现还是有坑。如果文件一直在增长,那么『最后两行』应该是程序执行当时文件的最后两行,步骤3里应该是『从倒数第二个回车符输出到步骤1中获取的文件大小位置』
1. 使用os.walk遍历所有的文件。<code class="language-text">def tail(filename, n=10):
'Return the last n lines of a file'
return deque(open(filename), n)
</code>