从文件中每隔 N 个(第 8 个字符)打印一次 [Python]
Printing every Nth (8th character) from a file [Python]
我从文件中转储了很长的位序列。现在,我想获取这个位序列并能够从中提取每第 8 位。例如:
100010010101000001001110010001110000110100001010
000110100000101000000000000000000000000000001101
010010010100100001000100010100100000000000000000
etc
会给出:
100110
(extraction from second line)
(extraction from third line)
etc
到目前为止我有以下代码:
#/usr/bin/python
with open("thebits.txt", 'r') as f:
content = [x.strip('\n') for x in f.readlines()]
{//logic to extract every 8th bit from each line and print it}
如何从每行中提取每第 8 位?
.
您可以使用简单的切片:
with open('thebits.txt', 'r') as f:
for line in f:
print line.strip()[7::8]
您的示例文件给出:
100110
000001
100000
切片 [7::8]
从第 8 个字符开始为您提供每第 8 个字符(7 从 0 开始索引)。
with open(infile) as f:
print("".join(line[7::8] for line in f))
假设您想要单独的每一行:
with open('tmp.txt', 'r') as f:
for line in f.read().splitlines():
print(line[7::8])
我从文件中转储了很长的位序列。现在,我想获取这个位序列并能够从中提取每第 8 位。例如:
100010010101000001001110010001110000110100001010
000110100000101000000000000000000000000000001101
010010010100100001000100010100100000000000000000
etc
会给出:
100110
(extraction from second line)
(extraction from third line)
etc
到目前为止我有以下代码:
#/usr/bin/python
with open("thebits.txt", 'r') as f:
content = [x.strip('\n') for x in f.readlines()]
{//logic to extract every 8th bit from each line and print it}
如何从每行中提取每第 8 位? .
您可以使用简单的切片:
with open('thebits.txt', 'r') as f:
for line in f:
print line.strip()[7::8]
您的示例文件给出:
100110
000001
100000
切片 [7::8]
从第 8 个字符开始为您提供每第 8 个字符(7 从 0 开始索引)。
with open(infile) as f:
print("".join(line[7::8] for line in f))
假设您想要单独的每一行:
with open('tmp.txt', 'r') as f:
for line in f.read().splitlines():
print(line[7::8])