【发布时间】:2017-02-16 08:20:36
【问题描述】:
我需要从大量 .txt 和 .csv 文件中提取前 2 行和最后一行。如何允许用户选择一个文件并输出一个新的 .txt 或 .csv 文件,其中只有这 3 行?
【问题讨论】:
我需要从大量 .txt 和 .csv 文件中提取前 2 行和最后一行。如何允许用户选择一个文件并输出一个新的 .txt 或 .csv 文件,其中只有这 3 行?
【问题讨论】:
这是你需要的:
def extract_lines(filename,outputname):
l = []
with open(filename,'r') as f:
for index,line in enumerate(f): #This iterates the file line by line which is memory efficient in case the csv is huge.
if index < 2: #first 2 lines
l.append(line)
if index > 1: # means the file has at least 3 lines
l.append(line)
with open(outputname,'w') as f:
for line in l:
f.write(line)
【讨论】:
if 就不需要对每一行都进行评估,这对于大文件可能需要一些时间。
seek。
def get_lines(filename, front=2, rear=1):
result = []
with open(filename, 'rb') as f:
for i, val in enumerate(f):
if i >= front:
break
result.append(val)
back_pos = -2
f.seek(back_pos, 2) # jump to the second end byte
rear_count = 0
while True:
if '\n' in f.read(1):
rear_count += 1
if rear_count >= rear:
result.extend(f.readlines())
break
back_pos -= 1
f.seek(back_pos, 2)
return result
阅读第一行很容易,但很难阅读最后一行。 迭代行非常慢。
【讨论】:
我想你也可以使用 bash 脚本来实现这个需求。
#!/bin/bash
for file in $(find . -name '*.txt' -o -name '*.csv' )
do
sed -n -e '1,2p' -e '$p' ${file} > "result"${file:(-5)}
done
此脚本将搜索所有以 txt 或 csv 结尾的文件。它会剪切前两行和最后一行,将这些行存储在一个新文件中。
比如我有三个文件,分别命名为file1.txt、file2.txt、file3.csv,它会为每个文件剪掉三行,分别存放在result1.txt、result2.txt、result3.csv中。
【讨论】:
这样你就可以返回你想要的行,只是使用范围的问题
df=open(r"D:\...\nameFile.txt",encoding='utf8')
def etiqueta(df):
lista=[]
for line,x in zip(df,range(0,2)):
lista.append(line)
return lista
etiqueta(df)
【讨论】: