我需要从大量的.txt和.csv文件中提取的第2排和最后一排。我如何允许用户选择一个文件,并输出一个新的.txt或.csv文件,只有这3行?提取前两排和最后一排从.txt或.csv的Python
0
A
回答
1
这是你所需要的:
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)
0
我想你也可以使用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中。
+0
这个问题上没有'bash'标签,所以你的回答不是有效的。 –
1
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
很容易读第一行,但很难读最后一行。 到iter行很慢。
相关问题
- 1. Python - 从txt文件读取前两行
- 2. Python的排序与和CSV
- 3. 获取最后一排的MYSQL
- 4. 更新重复数据从最后一排一排
- 5. 从最后一页中排除页眉
- 6. 查询获取排除最后一行的最后n行
- 7. 如何通过最后一排和列
- 8. Python Pandas从.csv提取列
- 9. Excel VBA中选择最后一排和最后一列
- 10. PHP不为最后一排
- 11. 只插入最后一排
- 12. 如何从python的.txt文件中提取两列?
- 13. 从qt中的.txt或.csv文件读取一行(Qt Quick)
- 14. Python的TXT提取器和组织者
- 15. 如何提取最新的排
- 16. 从表格中找到排名前两位的最小值
- 17. python - 从最后一行读取csv文件
- 18. 用python排序csv文件
- 19. 前端或后端数组排序
- 20. TListView列排序(按前两列排序)
- 21. 谷歌表 - 最后一排前至少一年找到一行
- 22. 排除前(或最后)在Rails中“每个”
- 23. 两排布局在一排
- 24. 读取,合并和排序.csv文件
- 25. 排序后排列两次阵列
- 26. Python的排序列表的最后一个地方
- 27. gatling和csv(从csv提取数据)
- 28. 添加类的最后一排elememts在
- 29. jQuery的:让最后一排栏选择
- 30. 参考不同片的最后一排
惊人的,谢谢! – mbf94
感谢您接受我的回答! –
如果 – Adirio