Tutorials  /  Python

Python File Operations: Leitfaden

Ccentron Redaktion · Februar 2024 ·4 Min. Lesezeit ·Python, Tutorial

In this tutorial, we’ll cover various file operations in Python. We’ll explore how to read, write, copy, and delete files, among other tasks. Let’s get started.

Why Are File Operations in Python Important?

When working with large datasets, especially in machine learning projects, handling files becomes essential. Since Python is widely used in data science, mastering its file operations is crucial.

1. Opening a File in Python Using the open() Function

The first step in working with files in Python is opening a file. You can open files using the open() function.

The open() function accepts two arguments: the filename with its full path and the mode in which the file should be opened. Common modes include:

  • 'r': Opens the file for reading (default mode).
  • 'w': Opens the file for writing. If the file doesn’t exist, it is created. If it exists, its content is overwritten.
  • 'a': Opens the file for appending. If the file doesn’t exist, it is created.
  • 'r+': Opens the file for both reading and writing.

Additionally, you can append 'b' to access the file in binary mode, e.g., 'rb' or 'wb'.

Example:

Python
with open('file.txt', 'r') as file:
content = file.read()
print(content)
# The file is automatically closed when the block is exited

2. Reading and Writing Files in Python

After opening a file, you can read its content using various methods:

  • read(size): Reads the entire file or a specified number of bytes.
  • readline(): Reads a single line from the file.
  • readlines(): Reads all lines from the file and returns them as a list.

Example:

with open('example.txt', 'r') as file:

# Read the entire file

content = file.read()

print(content)

# Reset the file pointer to the beginning

file.seek(0)

# Read the file line by line

for line in file:

print(line.strip())

Code

3. Writing to Files in Python

To write to a file, open it in write ('w'), append ('a'), or read/write mode ('r+' or 'w+').

Example:

# Writing to a new file or overwriting an existing file

with open('output.txt', 'w') as file:

file.write('This is a new line.\n')

# Appending to an existing file

with open('output.txt', 'a') as file:

file.write('This is an appended line.\n')

Code

Note: Opening a file in write mode ('w') overwrites its content. To prevent this, use append mode ('a') or check if the file exists beforehand.

4. Copying Files in Python Using the shutil Module

The shutil module offers a simple way to copy files:

import shutil

source = 'example.txt'

destination = 'example_copy.txt'

shutil.copy2(source, destination)

The copy2() function copies both the content and metadata of the file.

5. Deleting Files in Python Using the os Module

To delete a file, use the remove() function from the os module.

import os

file = 'example_copy.txt'

if os.path.exists(file):

os.remove(file)

print(f'{file} has been deleted.')

else:

print(f'{file} does not exist.')

Code

6. Handling File Paths

Managing file paths is crucial to avoid errors like FileNotFoundError. Always provide the correct file paths when working with files.

Example:

import os

file_path = '/Users/john/Desktop/example.txt'

if os.path.exists(file_path):

with open(file_path, 'r') as file:

print(file.read())

else:

print(f'File not found: {file_path}')

Code

Common errors such as FileNotFoundError can be avoided by checking the file's existence using os.path.exists().

VM

Passende Infrastruktur bei centron

Skripte und Dienste brauchen irgendwann eine Umgebung, die durchläuft: ccloud³ VMs ab 3,12 € im Monat, stundengenau abgerechnet. Cloud Server mieten →

Conclusion: Python File Operations

These are the core file operations in Python. Additionally, Python provides powerful tools for reading and writing CSV files, handling JSON data, and more. Mastering these operations is key to efficient data handling and manipulation.

Now it’s your turn! Practice these operations and integrate them into your Python projects.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Python
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren