To shuffle a directory in Python, you can use the following code:
```python
import random
def shuffle_directory(directory):
"""Shuffles the contents of a directory.
Args:
directory: The directory to shuffle.
Returns:
None.
"""
# Get the list of files in the directory.
files = os.listdir(directory)
# Shuffle the list of files.
random.shuffle(files)
# Iterate over the shuffled list of files and move them to a new directory.
for file in files:
os.rename(os.path.join(directory, file), os.path.join(directory, "shuffled", file))
```
This code will first get the list of files in the directory. It will then shuffle the list of files using the random.shuffle() function. Finally, it will iterate over the shuffled list of files and move them to a new directory called "shuffled".
Here is an example of how to use the shuffle_directory() function:
```python
# Create a directory to shuffle.
directory = "/tmp/shuffle"
# Create some files in the directory.
for i in range(10):
file = "file_" + str(i) + ".txt"
with open(os.path.join(directory, file), "w") as f:
f.write("This is file " + str(i) + ".")
# Shuffle the directory.
shuffle_directory(directory)
# Check the contents of the shuffled directory.
for file in os.listdir(directory):
with open(os.path.join(directory, file), "r") as f:
print(f.read())
```
This code will create a directory called "/tmp/shuffle" and create 10 files in it. It will then shuffle the directory and print the contents of the shuffled directory. The output of this code will be a random order of the 10 files.
No comments:
Post a Comment