saving file
Closed this issue · 1 comments
zwardnz commented
Hi, I'm new to both python and pybedtools.
I have tried to find a clear explanation in the documentation but am still stuck.
I have the following:
import pybedtools
enhancers = pybedtools.BedTool('enhancers.bed')
my_data = pybedtools.BedTool('mydata.bed')
# start with finding the closest enhancers to my novels
en_nearby = enhancers.closest(my_data, d=True, wb=True)
for enhancer in en_nearby:
if int(enhancer[-1]) <= 5000 and int(enhancer[-1]) >= 0:
print(enhancer, end="")
This is all good but instead of printing this I want to save this to an output file.
I have tried:
for enhancer in en_nearby:
if int(enhancer[-1]) <= 5000 and int(enhancer[-1]) >= 0:
print(enhancer, end="")
out = enhancer
out.saveas('enhancer.bed')
But get:
AttributeError: 'pybedtools.cbedtools.Interval' object has no attribute 'saveas'
daler commented
In your example it looks like you want to print each interval separately. Much of pybedtools usage can be "vectorized", that is doing operations on the entire file at once rather than in for-loops.
The each()
and filter()
methods are useful for this. I would try something like the following:
import pybedtools
enhancers = pybedtools.BedTool('enhancers.bed')
my_data = pybedtools.BedTool('mydata.bed')
en_nearby = enhancers.closest(my_data, d=True, wb=True)
def keep(x):
return 0 <= int(x[-1]) <= 5000
en_nearby.filter(keep).saveas('enhancer.bed')