Let me start by saying I'm fairly new to python.
Ok so I'm running code to perform physics calculations/draw graphs etc on data files, and what I need to do is loop over a number of files and sub-files. But the problem is there are a different number of sub-files in each file (e.g. file 0 has 711 sub-files, file 1 has 660 odd). It obviously doesn't like it when I run it across a file that doesn't have a sub-file at index x, so I was wondering is there a way to get it to run (iterate?) up to the final limit in each file automatically?
What I've got is a nested loop like:
for i in range(0,120):
for j in range(0,715):
stuff
Cheers in advance for any help, and sorry if my explanation is bad!
Edit:
some more of the code. So what I'm actually doing is calculating/plotting the angular momentum of gas and dark matter particles. These are in halos (j), & there are a number of files (i) containing lots and lots of these halos.
import getfiby
import numpy as np
import pylab as pl
angmom=getfiby.ReadFIBY("B")
for i in range(0,120):
for j in range(0,715):
pos_DM = angmom.getParticleField(49,i,j,"DM","Coordinates")
vel_DM = angmom.getParticleField(49,i,j,"DM","Velocity")
mass_DM = angmom.getParticleField(49,i,j,"DM","Mass")
more stuff
getfiby is a code I was given that retrieves all the data from the files (that I can't see). It's not really a massive problem, as I can still get it to run the calculations & make plots even if the upper limit I put on my range for j exceeds the number of halos there are in a particular file (I get: Halo index out of bounds. Goodbye.) But yeah I just wondered if there was a nicer, tidier way of getting it to run.
You may want something like this:
a=range(3)
for i in range(5):
try:
b=a[i] #if you iterate over your "subfiles" by index
except IndexError:
break #break out when list index out of range
When you build the list of files and subfiles to process, you could have the list in a variable named filelist and the subfile list in a variable called subfilelist You could then run the loops as
for myfile in filelist:
# Process code
for subfile in subfilelist:
# Process code.
If you need to use a range then
filerange = len(filelist)
subfilerange = len(subfilelist)
for i in range(0, filerange):
for j in range(0, subfilerange):
I may be misunderstanding your structure/intent here, but it sounds like you want to perform some calculations on each file in some folder structure, where the folders contain various numbers of the data files. In that case, I'd make use of the os.listdir function rather than trying to manually index each data file.
import os
for file in os.listdir(ROOT_DIRECTORY):
for subfile in os.listdir(os.path.join(ROOT_DIRECTORY, file)):
process(os.path.join(ROOT_DIRECTORY, file, subfile)) # or whatever
This can of course be made a little easier to look at in a few ways (personally I have my own listdir wrapper that returns full paths instead of just the basenames), but that would be my basic idea.
If you also need the index of each file, you can probably get it using some combination of enumerate and maybe sorted (e.g. for i, file in enumerate(sorted(os.listdir(...)))), but the specifics obviously depend on your filenames and directory structure.
Assuming fileSet is an iterable full of file objects, and each file object is itself an iterable full of subfile objects, than:
for i,file in enumerate(fileSet):
for j,subfile in enumerate(file):
stuff
But think hard about whether you really need the indices i and j, as you already have the words file and subfile to refer to the objects you are dealing with. If you don't need the indices, it's simply:
for file in fileSet:
for subfile in file:
stuff
Now, if by "file" you actually meant files in the Operating System's Filesystem, then I need you to explain me what a subfile is in that context, as Filesystem files usually cannot be nested, only directories can.
Related
Please help with trying to print the filenames of the pictures. I either print the same filename or the same picture with different filename.
I want the output to be FileName then Pic associated with FileName.
Instead I am getting FileName0 and Pic0 then FileName0 then Pic1
or Filename0 then Pic0 then Filename1 then Pic0.
I added more code to the original post for clarification of what I was trying to do. Hopefully I/it makes sense. I want to print the name of the image and then display the image. The new code I came up with displays the image then prints the name at them bottom of it with none and then the program terminates. Say the list has 4 images. I want to print the name at image[0] and then display image[0] in a loop and then print image[1] display image[1]
#OLD CODE
with zipfile.ZipFile("file.zip", 'r') as zip_ref:
zip_ref.extractall("folderName")
for info in zip_ref.infolist():
for file in os.listdir("folderName"):
image=Image.open(file).convert('RGB')
print(info.filename)
display(image)
#NEW CODE
#My current list length is 4
file_name = []
actual_image = []
##Extract all the files and put in folder
with zipfile.ZipFile("readonly/small_img.zip", 'r') as zip_ref:
zip_ref.extractall("pyproject")
#Add name to list/Add image to list. Probably should be one list.
for entry in os.scandir("pyproject"):
file_name.append(entry.name)
for file in os.listdir("pyproject"):
image=Image.open(file).convert('RGB')
actual_image.append(image)
#print(info.filename,display(image))
#Newer line of code directly above.
#When the above for loop becomes nested it displays 4
#pictures with the file number underneath. Expected result is 1pic to 1 filename.
#Its closer to what I want. Will keep trying.
print(len(file_name))
#Returns file names.
def name_of_file(a):
for names in a:
return names
#Returns image to be displayed
def image_of_file(b):
for image in b:
return (display(image))
##Prints out image name and then displays image
print(name_of_file(file_name),image_of_file(actual_image))
###Dictionary example code:
list_of_pictures = [{image1_of_four :PIL.image,bounding_box,pytesseract_text}]
I think the confusion comes from the double iteration. As far as I can see, this is not necessary, because you just want to iterate over every (image) file in a zipped directory. (If I have understood the question correctly.)
A single iteration is sufficient here:
import zipfile
with zipfile.ZipFile("file.zip", 'r') as zip_ref:
for file in zip_ref.filelist:
print(file.filename)
# ...
So for processing the files inside the zip archive you could do something like this (of course there are several possibilities, depending on the usecase):
import zipfile
from PIL import Image, UnidentifiedImageError
with zipfile.ZipFile("file.zip", 'r') as zip_ref:
for zipped_file in zip_ref.filelist:
print(f"This is your fileinfo: {zipped_file.filename}")
try:
file = zip_ref.open(zipped_file)
image = Image.open(file).convert('RGB')
except UnidentifiedImageError:
print(f"Error processing {zipped_file.filename}")
If you really need more information from the iterated (zipped) files, then the infolist() method is ok, giving you the information from ZipInfo-object.
Update after question editing:
As far as I can see, there is still a picture to be displayed and the corresponding file name to be printed. If my assumption is correct, then there are several issues with the presented code:
There is no need at all to iterate several times. No matter if you have one nested iteration or several iterations in a row. Limiting the number of iterations also reduces the complexity and probably the whole thing becomes less complicated. To go into detail: You use several iterations to 1. unzip the files (zip_ref.extractall() is already iterating itself), 2. store the filenames in a list, 3. store the image objects in a list, 4. print the stored filenames, 5. display the image objects. All information is already available to you when iterating over the files in the archive, or can be easily computed in the current iteration step. This completely eliminates the need to create multiple data structures for file names, image objects etc. Here you already have the file, thus also the file name and thus also the corresponding image.
I still see no reason to unpack the whole archive first. All this can be done in the iteration itself. If the images themselves are to be saved, then unpacking is of course useful. But then you can also simply unzip the files and then iterate over the unzipped files with Python, e.g. with os.scandir(). This was implemented in the updated code. But this is not necessary if you only want to display the current file of each iteration step.
Unfortunately the function of display() is still not known to me. Probably something similar to Image.show() is done there. After the code update within the question, I can only mention small changes to my example to show how easy it can be to display the file name for the corresponding image:
import os
import zipfile
from PIL import Image, UnidentifiedImageError
with zipfile.ZipFile("file.zip", 'r') as zip_ref:
for zipped_file in zip_ref.filelist:
try:
image = Image.open(zip_ref.open(zipped_file)).convert('RGB')
print(os.path.basename(zipped_file.filename))
image.show() # simulating: display(image)
input("Press a key to show next image...")
except UnidentifiedImageError:
pass
I only print the file name, for which there is also a matching picture. No other prints (to keep things as clear as possible). image.show() is used to simulate the unknown display(image)-function. To make it clear that the corresponding file name refers to the currently opened image, I have included a pause, here in the form of a user prompt (input()).
All this under the assumption that simply the appropriate file name for a certain image should be displayed. Using only one iteration should be the appropriate solution here.
Using multiple iterations to store objects in multiple lists (as done in the question) leads to a disadvantage: Higher complexity. In this case, the index positions of the lists have to match each other, and when iterating over one list, you have to access the other list with the same index position like this:
list_a = [1, 2, 3]
list_b = ["a", "b", "c"]
for index, el in enumerate(list_a):
print(el, list_b[index])
You have to do this without changing much of your code. But then you have to make sure that the lists never change (or rather use tuples) and this is simply more complex (and also more complicated). See also this.
I have a problem that I have not been able to solve. I have 4 .txt files each between 30-70GB. Each file contains n-gram entries as follows:
blabla1/blabla2/blabla3
word1/word2/word3
...
What I'm trying to do is count how many times each item appear, and save this data to a new file, e.g:
blabla1/blabla2/blabla3 : 1
word1/word2/word3 : 3
...
My attempts so far has been simply to save all entries in a dictionary and count them, i.e.
entry_count_dict = defaultdict(int)
with open(file) as f:
for line in f:
entry_count_dict[line] += 1
However, using this method I run into memory errors (I have 8GB RAM available). The data follows a zipfian distribution, e.g. the majority of the items occur only once or twice.
The total number of entries is unclear, but a (very) rough estimate is that there is somewhere around 15,000,000 entries in total.
In addition to this, I've tried h5py where all the entries are saved as a h5py dataset containing the array [1], which is then updated, e.g:
import h5py
import numpy as np
entry_count_dict = h5py.File(filename)
with open(file) as f:
for line in f:
if line in entry_count_dict:
entry_count_file[line][0] += 1
else:
entry_count_file.create_dataset(line,
data=np.array([1]),
compression="lzf")
However, this method is way to slow. The writing speed gets slower and slower. As such, unless the writing speed can be increased this approach is implausible. Also, processing the data in chunks and opening/closing the h5py file for each chunk did not show any significant difference in processing speed.
I've been thinking about saving entries which start with certain letters in separate files, i.e. all the entries which start with a are saved in a.txt, and so on (this should be doable using defaultdic(int)).
However, to do this the file have to iterated once for every letter, which is implausible given the file sizes (max = 69GB).
Perhaps when iterating over the file, one could open a pickle and save the entry in a dict, and then close the pickle. But doing this for each item slows down the process quite a lot due to the time it takes to open, load and close the pickle file.
One way of solving this would be to sort all the entries during one pass, then iterate over the sorted file and count the entries alphabetically. However, even sorting the file is painstakingly slow using the linux command:
sort file.txt > sorted_file.txt
And, I don't really know how to solve this using python given that loading the whole file into memory for sorting would cause memory errors. I have some superficial knowledge of different sorting algorithms, however they all seem to require that the whole object to be sorted needs get loaded into memory.
Any tips on how to approach this would be much appreciated.
There are a number of algorithms for performing this type of operation. They all fall under the general heading of External Sorting.
What you did there with "saving entries which start with certain letters in separate files" is actually called bucket sort, which should, in theory, be faster. Try it with sliced data sets.
or,
try Dask, a DARPA + Anaconda backed distributive computing library, with interfaces familiar to numpy, pandas, and works like Apache-Spark. (works on single machine too)
btw it scales
I suggest trying dask.array,
which cuts the large array into many small ones, and implements numpy ndarray interface with blocked algorithms to utilize all of your cores when computing these larger-than-memory datas.
I've been thinking about saving entries which start with certain letters in separate files, i.e. all the entries which start with a are saved in a.txt, and so on (this should be doable using defaultdic(int)). However, to do this the file have to iterated once for every letter, which is implausible given the file sizes (max = 69GB).
You are almost there with this line of thinking. What you want to do is to split the file based on a prefix - you don't have to iterate once for every letter. This is trivial in awk. Assuming your input files are in a directory called input:
mkdir output
awk '/./ {print $0 > ( "output/" substr($0,0,1))}` input/*
This will append each line to a file named with the first character of that line (note this will be weird if your lines can start with a space; since these are ngrams I assume that's not relevant). You could also do this in Python but managing the opening and closing of files is somewhat more tedious.
Because the files have been split up they should be much smaller now. You could sort them but there's really no need - you can read the files individually and get the counts with code like this:
from collections import Counter
ngrams = Counter()
for line in open(filename):
ngrams[line.strip()] += 1
for key, val in ngrams.items():
print(key, val, sep='\t')
If the files are still too large you can increase the length of the prefix used to bucket the lines until the files are small enough.
I've got this:
files = glob.glob(str(dir_path) + "*.fa")
index = SeqIO.index_db(index_filename, files, "fasta")
seq = index[accession] # Slow
index.close()
return seq
and i'm working on big files (gene sequences) but for some reasons, it takes about 4 secondes to get the sequence I'm looking for. I'm wondering if the index_db method is suppose to be that slow? Am I using the right method?
Thanks.
The first time the database is created it can take some time. The next times, if you don't delete the index_filename created, it should go faster.
Lets say you have your 25 files each with some genes. This method creates a SQLite DB that helps locating the sequences among the files, like "Get me the gene XXX" and the SQLite/index_db knows that the gene is in the file 12.fasta and its exact location inside the file. So Biopython opens the file and scans quickly to the gene position.
Without that index_db you have to load every Records into memory, which is fast but some files might not fit in the RAM.
If you want speed to fetch regions you can use FastaFile from pysam and samtools. Like this:
You have to index all the fasta files with faidx:
$ samtools faidx big_fasta.fas
From your code write something like this:
from pysam import FastaFile
rec = FastaFile("big_fasta.fas") # big_fasta.fas.fai must exist.
seq = rec.fetch(reference=gene_name, start=1000, end= 1200)
print(s)
In my computer this times 2 orders of magnitude faster than Biopython for the same operation, but you only get the pure sequence of bases.
I have a file that has over 200 lines in this format:
name old_id new_id
The name is useless for what I'm trying to do currently, but I still want it there because it may become useful for debugging later.
Now I need to go through every file in a folder and find all the instances of old_id and replace them with new_id. The files I'm scanning are code files that could be thousands of lines long. I need to scan every file with each of the 200+ ids that I have, because some may be used in more than one file, and multiple times per file.
What is the best way to go about doing this? So far I've been creating python scripts to figure out the list of old ids and new ids and which ones match up with each other, but I've been doing it very inefficient because I basically scanned the first file line by line and got the current id of the current line, then I would scan the second file line by line until I found a match. Then I did this over again for each line in the first file, which ended up with my reading the second file a lot. I didn't mind doing this inefficiently because they were small files.
Now that I'm searching probably somewhere around 30-50 files that can have thousands of line of code in it, I want it to be a little more efficient. This is just a hobbyist project, so it doesn't need to be super good, I just don't want it to take more than 5 minutes to find and replace everything, then look at the result and see that I made a little mistake and need to do it all over again. Taking a few minutes is fine(although I'm sure with computers nowadays they can do this almost instantly still) but I just don't want it to be ridiculous.
So what's the best way to go about doing this? So far I've been using python but it doesn't need to be a python script. I don't care about elegance in the code or way I do it or anything, I just want an easy way to replace all of my old ids with my new ids using whatever tool is easiest to use or implement.
Examples:
Here is a line from the list of ids. The first part is the name and can be ignored, the second part is the old id, and the third part is the new id that needs to replace the old id.
unlock_music_play_grid_thumb_01 0x108043c 0x10804f0
Here is an example line in one of the files to be replaced:
const v1, 0x108043c
I need to be able to replace that id with the new id so it looks like this:
const v1, 0x10804f0
Use something like multiwordReplace (I've edited it for your situation) with mmap.
import os
import os.path
import re
from mmap import mmap
from contextlib import closing
id_filename = 'path/to/id/file'
directory_name = 'directory/to/replace/in'
# read the ids into a dictionary mapping old to new
with open(id_filename) as id_file:
ids = dict(line.split()[1:] for line in id_file)
# compile a regex to do the replacement
id_regex = re.compile('|'.join(map(re.escape, ids)))
def translate(match):
return ids[match.group(0)]
def multiwordReplace(text):
return id_regex.sub(translate, text)
for code_filename in os.listdir(directory_name):
with open(os.path.join(directory, code_filename), 'r+') as code_file:
with closing(mmap(code_file.fileno(), 0)) as code_map:
new_file = multiword_replace(code_map)
with open(os.path.join(directory, code_filename), 'w') as code_file:
code_file.write(new_file)
this is similar to the question in merge sort in python
I'm restating because I don't think I explained the problem very well over there.
basically I have a series of about 1000 files all containing domain names. altogether the data is > 1gig so I'm trying to avoid loading all the data into ram. each individual file has been sorted using .sort(get_tld) which has sorted the data according to its TLD (not according to its domain name. sorted all the .com's together, .orgs together, etc)
a typical file might look like
something.ca
somethingelse.ca
somethingnew.com
another.net
whatever.org
etc.org
but obviosuly longer.
I now want to merge all the files into one, maintaining the sort so that in the end the one large file will still have all the .coms together, .orgs together, etc.
What I want to do basically is
open all the files
loop:
read 1 line from each open file
put them all in a list and sort with .sort(get_tld)
write each item from the list to a new file
the problem I'm having is that I can't figure out how to loop over the files
I can't use with open() as because I don't have 1 file open to loop over, I have many. Also they're all of variable length so I have to make sure to get all the way through the longest one.
any advice is much appreciated.
Whether you're able to keep 1000 files at once is a separate issue and depends on your OS and its configuration; if not, you'll have to proceed in two steps -- merge groups of N files into temporary ones, then merge the temporary ones into the final-result file (two steps should suffice, as they let you merge a total of N squared files; as long as N is at least 32, merging 1000 files should therefore be possible). In any case, this is a separate issue from the "merge N input files into one output file" task (it's only an issue of whether you call that function once, or repeatedly).
The general idea for the function is to keep a priority queue (module heapq is good at that;-) with small lists containing the "sorting key" (the current TLD, in your case) followed by the last line read from the file, and finally the open file ready for reading the next line (and something distinct in between to ensure that the normal lexicographical order won't accidentally end up trying to compare two open files, which would fail). I think some code is probably the best way to explain the general idea, so next I'll edit this answer to supply the code (however I have no time to test it, so take it as pseudocode intended to communicate the idea;-).
import heapq
def merge(inputfiles, outputfile, key):
"""inputfiles: list of input, sorted files open for reading.
outputfile: output file open for writing.
key: callable supplying the "key" to use for each line.
"""
# prepare the heap: items are lists with [thekey, k, theline, thefile]
# where k is an arbitrary int guaranteed to be different for all items,
# theline is the last line read from thefile and not yet written out,
# (guaranteed to be a non-empty string), thekey is key(theline), and
# thefile is the open file
h = [(k, i.readline(), i) for k, i in enumerate(inputfiles)]
h = [[key(s), k, s, i] for k, s, i in h if s]
heapq.heapify(h)
while h:
# get and output the lowest available item (==available item w/lowest key)
item = heapq.heappop(h)
outputfile.write(item[2])
# replenish the item with the _next_ line from its file (if any)
item[2] = item[3].readline()
if not item[2]: continue # don't reinsert finished files
# compute the key, and re-insert the item appropriately
item[0] = key(item[2])
heapq.heappush(h, item)
Of course, in your case, as the key function you'll want one that extracts the top-level domain given a line that's a domain name (with trailing newline) -- in a previous question you were already pointed to the urlparse module as preferable to string manipulation for this purpose. If you do insist on string manipulation,
def tld(domain):
return domain.rsplit('.', 1)[-1].strip()
or something along these lines is probably a reasonable approach under this constraint.
If you use Python 2.6 or better, heapq.merge is the obvious alternative, but in that case you need to prepare the iterators yourself (including ensuring that "open file objects" never end up being compared by accident...) with a similar "decorate / undecorate" approach from that I use in the more portable code above.
You want to use merge sort, e.g. heapq.merge. I'm not sure if your OS allows you to open 1000 files simultaneously. If not you may have to do it in 2 or more passes.
Why don't you divide the domains by first letter, so you would just split the source files into 26 or more files which could be named something like: domains-a.dat, domains-b.dat. Then you can load these entirely into RAM and sort them and write them out to a common file.
So:
3 input files split into 26+ source files
26+ source files could be loaded individually, sorted in RAM and then written to the combined file.
If 26 files are not enough, I'm sure you could split into even more files... domains-ab.dat. The point is that files are cheap and easy to work with (in Python and many other languages), and you should use them to your advantage.
Your algorithm for merging sorted files is incorrect. What you do is read one line from each file, find the lowest-ranked item among all the lines read, and write it to the output file. Repeat this process (ignoring any files that are at EOF) until the end of all files has been reached.
#! /usr/bin/env python
"""Usage: unconfuse.py file1 file2 ... fileN
Reads a list of domain names from each file, and writes them to standard output grouped by TLD.
"""
import sys, os
spools = {}
for name in sys.argv[1:]:
for line in file(name):
if (line == "\n"): continue
tld = line[line.rindex(".")+1:-1]
spool = spools.get(tld, None)
if (spool == None):
spool = file(tld + ".spool", "w+")
spools[tld] = spool
spool.write(line)
for tld in sorted(spools.iterkeys()):
spool = spools[tld]
spool.seek(0)
for line in spool:
sys.stdout.write(line)
spool.close()
os.remove(spool.name)