- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试从 bz2 文件中提取 10'000 行。
import bz2
file = "file.bz2"
file_10000 = "file.txt"
output_file = codecs.open(file_10000,'w+','utf-8')
source_file = bz2.open(file, "r")
count = 0
for line in source_file:
count += 1
if count < 10000:
output_file.writerow(line)
但我得到一个错误“‘模块’对象没有属性‘打开’”。你有什么想法?或者我可以通过其他方式将 10'000 行保存到 txt 文件中吗?我在 Windows 上。
最佳答案
这是一个完整的示例,其中包括编写和读取一个比您的 10000 行小得多的测试文件。很高兴在问题中有工作示例,这样我们就可以轻松测试。
import bz2
import itertools
import codecs
file = "file.bz2"
file_10000 = "file.txt"
# write test file with 9 lines
with bz2.BZ2File(file, "w") as fp:
fp.write('\n'.join('123456789'))
# the original script using BZ2File ... and 3 lines for test
# ...and fixing bugs:
# 1) it only writes 9999 instead of 10000
# 2) files don't do writerow
# 3) close the files
output_file = codecs.open(file_10000,'w+','utf-8')
source_file = bz2.BZ2File(file, "r")
count = 0
for line in source_file:
count += 1
if count <= 3:
output_file.write(line)
source_file.close()
output_file.close()
# show what you got
print('---- Test 1 ----')
print(repr(open(file_10000).read()))
一种更有效的方法是在阅读所需行后跳出 for
循环。您甚至可以像这样利用迭代器来精简代码:
# a faster way to read first 3 lines
with bz2.BZ2File(file) as source_file,\
codecs.open(file_10000,'w+','utf-8') as output_file:
output_file.writelines(itertools.islice(source_file, 3))
# show what you got
print('---- Test 2 ----')
print(repr(open(file_10000).read()))
关于python - 在 python 中读取 bz2 文件的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37172679/
我应该如何在 lex(或 flex)中进行编程以从文本中删除嵌套注释并仅打印不在注释中的文本?我可能应该以某种方式识别我在评论中时的状态以及 block 评论的起始“标签”的数量。 让我们制定规则:
我按照 bz's demo 创建了一个可调整大小的表格列代码 但是当我创建超过 30 个列时,代码不起作用。我正在创建的表格非常简单: Column 1
我从我的教授那里得到了这个问题。 取一个整数 N 和一个具有 X 个整数的数组 A(非空)。您需要将数组 A 分成两部分,第一个数组 Ax(左数组)包含等于整数 N 的数字,数组 Ay(右数组)包含相
我发现很多页面都在说明如何解压 tar.bz2 文件,但是如何解压 tar.bz 文件呢? 最佳答案 使用 tar 的 -j 选项。 tar -xjf /path/to/archive.tar.bz
我想写一个匹配的正则表达式 a a-b 但前提是这些序列后面没有 Z ((a(-b)?)(?!Z)) a matches a ok a-b matches a-b
我正在尝试运行一些面部正面化代码(在 Windows10 上使用 Python3),该代码使用 opencv 和 dlib 并需要一个名为 shape_predictor_68_face_landma
尝试从 cassandra 执行 WordCount 示例并出现错误: 线程“主”java.lang.NoSuchMethodError 中的异常:org.apache.thrift.meta_dat
我正在尝试编写一个实用函数来打开三种不同类型的文件:.bz2、.gz 和 .txt。我不能只使用 File.read,因为它会返回压缩文件的垃圾。我正在尝试使用 Open3.popen3 以便我可以给
我是一名优秀的程序员,十分优秀!