Python file system operations examples

Sidney 87 Published: 10/23/2024

Python file system operations examples

I'll respond in English this time! Here are some Python file system operations examples:

Creating a new directory:
import os

os.mkdir("new_directory")

This will create a new directory named "new_directory" in the current working directory.

Deleting a directory:

import os

os.rmdir("directory_to_delete")

Replace "directory_to_delete" with the actual name of the directory you want to delete. Be careful when using this method, as it permanently deletes the directory and all its contents!

Creating a new file:
open("new_file.txt", "w").write("Hello World!")

This will create a new text file named "new_file.txt" in the current working directory with the content "Hello World!".

Writing to an existing file:
with open("existing_file.txt", "a") as f:

f.write("Additional content!")

In this example, we're appending additional content to an existing file named "existing_file.txt".

Reading from a file:
with open("file_to_read.txt", "r") as f:

print(f.read())

This will read the contents of a file named "file_to_read.txt" and print it to the console.

Renaming a file or directory:
import os

os.rename("old_file.txt", "new_file.txt")

Replace "old_file.txt" with the actual name of the file you want to rename, and "new_file.txt" with the desired new name.

Checking if a file or directory exists:
import os

if os.path.exists("file_to_check.txt"):

print("File exists!")

else:

print("File does not exist!")

Replace "file_to_check.txt" with the actual name of the file you want to check for existence.

Listing files and directories in a directory:
import os

for filename in os.listdir("directory_to_list"):

print(filename)

This will list all files and directories within the specified directory ("directory_to_list").

Copying a file:
import shutil

shutil.copyfile("source_file.txt", "destination_file.txt")

Replace "source_file.txt" with the actual name of the file you want to copy, and "destination_file.txt" with the desired destination file name.

Moving or renaming a directory:
import os

os.rename("old_directory", "new_directory")

Replace "old_directory" with the actual name of the directory you want to move or rename, and "new_directory" with the desired new name.

These examples should give you a good starting point for performing various file system operations in Python!

Python file function

Here's a brief overview of the Python language and its functions:

Python is a high-level programming language that is easy to learn and use. It's a popular choice for beginners and experienced developers alike because it has a simple syntax, is easy to read and write, and can be used for a wide range of applications.

In terms of functions, Python has several built-in functions that you can use in your code. For example:

The print() function: This function is used to print output to the screen. It's often used in conjunction with variables or expressions.

x = 5

print("The value of x is:", x)

The len() function: This function returns the length (number of characters) of a string.
my_string = "Hello, world!"

length = len(my_string)

print("The length of the string is:", length)

The range() function: This function generates a sequence of numbers that you can use in your code.
numbers = range(1, 6)  # generate a sequence from 1 to 5

for num in numbers:

print(num)

The map() function: This function applies a given function to each item of an iterable (such as a list or tuple).
def square(x):

return x * x

numbers = [1, 2, 3, 4, 5]

squared_numbers = map(square, numbers)

print(squared_numbers) # prints: [1, 4, 9, 16, 25]

The filter() function: This function constructs a new iterator from elements of an iterable for which a function returns true.
def is_even(x):

return x % 2 == 0

numbers = [1, 2, 3, 4, 5]

even_numbers = filter(is_even, numbers)

print(even_numbers) # prints: [2, 4]

The sorted() function: This function sorts the elements of an iterable in a specific order.
numbers = [4, 1, 3, 2]

sorted_numbers = sorted(numbers)

print(sorted_numbers) # prints: [1, 2, 3, 4]

The reduce() function: This function applies a rolling computation to sequential pairs of values in a list.
from functools import reduce

numbers = [1, 2, 3, 4, 5]

def add(x, y):

return x + y

sum_numbers = reduce(add, numbers)

print(sum_numbers) # prints: 15

These are just a few examples of the many functions that Python has to offer. With its wide range of built-in functions and ability to create your own custom functions, Python is a powerful language for any type of application you want to build.

Now that we've covered some of the basic concepts of Python, let's explore some more advanced topics in our next installment!