嘗試解壓縮文件時,出現錯誤,刪除我不感興趣的行,最後將其餘行寫入文件。這裏是我的代碼:解壓縮文件時,在將它們寫入文件之前刪除不需要的行
import gzip, os, sys
dataset_names=[]
dir_path=('local drive path')
dataset_names= os.listdir(dir_path)
count=0
read_zip = [];
for dataset in dataset_names:
each_dataset=os.path.join(dir_path+'\\'+dataset+'\\'+'soft'+'\\'+dataset+'_full'+'.soft')
with gzip.open(each_dataset+'.gz', 'rb') as each_gzip_file:
if count == 2: # I wanted to check with 2 datasets first
continue;
for line in each_gzip_file:
if line.startwith !=('#', '!', '^'):
continue;
read_zip.append('\t' + line);
with open('name of a file', 'wb') as f:
f.writelines(read_zip)
print(dataset);
count+=1;
這裏是我的錯誤:
AttributeError: 'bytes' object has no attribute 'startwith'
然後我試圖將其更改爲下面的代碼:
......
.......
for line in each_gzip_file:
if not PY3K:
if lines.startwith != ('#', '!', '^'):
continue;
lines.append(line)
else:
lines.append(line.decode('cp437'))
makeitastring = ''.join(map(str, lines))
with open('fine name', 'wb') as f:
my_str_as_bytes = str.encode(str(,lines))
f.writelines(makeitastring)
這一次得到這個錯誤:
TypeError: a bytes-like object is required, not 'str'
我也改變了它與以下,但它也沒有工作。這就像它一遍又一遍地迭代:
for line in each_gzip_file:
read_zip.append(line);
for x in read_zip:
if str(x).startswith != ('#', '!', '^'):
continue;
else:
final.append(x);
with open('file name', 'ab') as f:
f.writelines(final)
我錯過了什麼嗎? 謝謝,
你能指定哪一行實際觸發錯誤嗎? – Saustin
@Saustin for each_gzip_file中的行: if line.startwith!=('#','!','^'): continue; – NinaDev
你嘗試過'str(line).startwith!= ...'? – VBB