Tags down


Select a random file from a directory and send it (Python, MIME)

By : José Vildósola
Date : October 14 2020, 08:10 PM
I think the issue was by ths following , You select a random file and then throw it away (well, you print it, then throw it away):
code :
files = os.listdir(path)
index = random.randrange(0, len(files))
filename = files
attachment  = open(filename, 'rb')
attachment  = open(random.choice(files), 'rb')
attachment  = open(os.path.join(path, random.choice(files)), 'rb')

Share : facebook icon twitter icon

select random file from directory

By : sarthak
Date : March 29 2020, 07:55 AM
Any of those help select random file from directory
code :
private string getrandomfile2(string path)
        string file = null;
        if (!string.IsNullOrEmpty(path))
            var extensions = new string[] { ".png", ".jpg", ".gif" };
                var di = new DirectoryInfo(path);
                var rgFiles = di.GetFiles("*.*").Where( f => extensions.Contains( f.Extension.ToLower()));
                Random R = new Random();
                file = rgFiles.ElementAt(R.Next(0,rgFiles.Count())).FullName;
            // probably should only catch specific exceptions
            // throwable by the above methods.
            catch {}
        return file;

select random file from directory

Date : March 29 2020, 07:55 AM
like below fixes the issue Changed to use a single instance of the pseudo-random number generator.
code :
// Use a class variable so that the RNG is only created once.
private Random generator;
private Random Generator
        if (this.generator == null)
           this.generator = new Random();
        return this.generator;
private string getrandomfile(string path)
    string file = null;
    if (!string.IsNullOrEmpty(path))
        var extensions = new string[] { ".png", ".jpg", ".gif" };
            var di = new DirectoryInfo(path);
            var rgFiles = di.GetFiles("*.*")
                            .Where( f => extensions.Contains( f.Extension
                                                               .ToLower() );
            int fileCount = rgFiles.Count();
            if (fileCount > 0)
                int x = this.Generator.Next( 0, fileCount );
                file = rgFiles.ElementAt(x).FullName;
        // probably should only catch specific exceptions
        // throwable by the above methods.
        catch {}
    return file;

Select random file from directory

By : Jack
Date : March 29 2020, 07:55 AM
wish of those help You can use glob to get all files in a directory, and then take a random element from that array. A function like this would do it for you:
code :
function random_pic($dir = 'uploads')
    $files = glob($dir . '/*.*');
    $file = array_rand($files);
    return $files[$file];

PHP load directory select HTML file and send it via Mail

By : bhadram rao
Date : March 29 2020, 07:55 AM
I hope this helps . I set myself to a little PHP project. The aim of my project is to create a webapp which loads HTML emails from directory and send them out. , Try this code
code :

function LoadTemplate()
    foreach(glob(dirname(__FILE__) . '/templates/*') as $filename)
        echo "<option value='" . $filename . "'>" . basename($filename) . "</option>";
    $to = $_POST['recipient'];
    $subject = $_POST['subject'];
    $message = file_get_contents($_REQUEST['s1'], "r") or exit("Unable to open file");
    $headers = "Content-type: text/html\r\n";
    $mail_send = mail($to, $subject, $message, $headers);
     echo 'Mail Send ';
     echo 'Try Later';

    <form name="form1" method="post" action="mail.php">Send To:
        <input type="text" id="recipient" name="recipient">
        <input type="text" id="subject" name="subject">
        <select name="s1">
            <option value="" selected="selected">-----</option>
            <?php require( 'mail.php'); echo LoadTemplate(); ?>
            <input type="submit" value="Send" name='submit'>

How can I efficiently select 100 random JPG files from a directory (including subdirs) in Python?

By : Кристина Малькова
Date : March 29 2020, 07:55 AM
wish of those help See Generator Tricks for System Programmers for a bunch of neat stuff. But specifically, see the gen-find example. This is as efficient as you are going to get, without making a bunch of assumptions about your file structure layout.
Related Posts Related Posts :
  • String Manipulation Recursive Function
  • Filter after Groupby and Sum in pandas?
  • writing a custom function Multiply the average of x,y
  • Spotify API fetch authorization code from redirect_uri
  • sklearn use RandomizedSearchCV with custom metrics and catch Exceptions
  • IndexOutOfRange error when filling a List Python
  • sns stripplot with just top n number of categories
  • Python classes keep calling eachother
  • How do I create a Dataframe_new in python from an existing Dataframe_old.
  • calculating an intercept point between a straight line and an ellipse - python
  • Integrating Tensorflow object detection with keras cnn classifier
  • How to skip comma while reading CSV file in python?
  • Stop Integrating when Output Reaches 0 in scipy.integrate.odeint
  • Changing the current graph of tf.placeholder objects in Tensorflow: Is it possible?
  • Logical error in while statement when used with or operator
  • django-rest-framework: int() argument must be a string, a bytes-like object or a number, not Deferred Attribute
  • how to remove a whitespace in a list in python?
  • How to reduce the number of row repetitions in a numpy array
  • Python: Dividing values of nested list with values with values of dictionary
  • Printing empty Pyramid
  • Python: How to save log file toSharePoint
  • Python Pandas count most frequent occurrences
  • How can I store / cache values from methods in a class for later use in other methods of the same class?
  • Sklearn: Pass class names to make_scorer
  • PyTorch - applying attention efficiently
  • How do I capitalize each parameter in a function definition using Python?
  • Regex matching of a bytes pattern gives unusual results - '.' not equivalent to [\x00-\xff]
  • I need help converting this REST API Curl command to Python requests
  • How do you make a variable comparison to decide a better score in a dice game?
  • How do I run sumo-gui on instant-veins-4.7.1-i1.ova
  • Deal with NAN values when creating models with python
  • Python requests: having a space in header for posting
  • Adding a column to a pandas dataframe based on cell values
  • Get mongod rs.status() results from a python script
  • ImportError: C extension: No module named 'parsing' not built
  • python pandas update column values related to previous updated row during iteration over it
  • 3 nested loops: Optimizing a simple simulation for speed
  • Assign subset of values to pandas dataframe with MultiIndex
  • How to group two sets of buttons on each top corner of the screen using Tkinter?
  • django login using class based for custom user
  • MRJob sort reducer output
  • Python Pandas Counts using rolling time window
  • Getting or editing a string from a column in a csv file with pandas
  • Python - Delete row in matrix/array if row contains
  • Using dicom Images with OpenCV in Python
  • Odoo ghost record
  • Creating and assigning multiple variables in a tkinter application
  • Graph dictionary
  • No changes to original dataframe after applying loop
  • AUC of Random forest model is lower after tuning parameters using hypergrid search and CV with 10 folds
  • Python: Reading multiple CSV files, and assigning each to a different variable
  • How to identify empty rectangle using OpenCV
  • How to iterate multilevel dataframe in python
  • How to limit the contour plot with a line plot?
  • Why subclassing a str or int behaves differently from subclising a list or dict?
  • Python decode with translation table
  • i need to click unordered links in the below URL using selenium, python
  • How to join pandas dataframe with itself?
  • How to apply a color cast to a video frame in OpenCV Python?
  • Is there any existing library for median filtering with kernel size greater then 5 using OpenCL acceleration in python?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org