Fix "local variable referenced before assignment" in Python

local variable 'result' referenced before assignment python

Introduction

If you're a Python developer, you've probably come across a variety of errors, like the "local variable referenced before assignment" error. This error can be a bit puzzling, especially for beginners and when it involves local/global variables.

Today, we'll explain this error, understand why it occurs, and see how you can fix it.

The "local variable referenced before assignment" Error

The "local variable referenced before assignment" error in Python is a common error that occurs when a local variable is referenced before it has been assigned a value. This error is a type of UnboundLocalError , which is raised when a local variable is referenced before it has been assigned in the local scope.

Here's a simple example:

Running this code will throw the "local variable 'x' referenced before assignment" error. This is because the variable x is referenced in the print(x) statement before it is assigned a value in the local scope of the foo function.

Even more confusing is when it involves global variables. For example, the following code also produces the error:

But wait, why does this also produce the error? Isn't x assigned before it's used in the say_hello function? The problem here is that x is a global variable when assigned "Hello ". However, in the say_hello function, it's a different local variable, which has not yet been assigned.

We'll see later in this Byte how you can fix these cases as well.

Fixing the Error: Initialization

One way to fix this error is to initialize the variable before using it. This ensures that the variable exists in the local scope before it is referenced.

Let's correct the error from our first example:

In this revised code, we initialize x with a value of 1 before printing it. Now, when you run the function, it will print 1 without any errors.

Fixing the Error: Global Keyword

Another way to fix this error, depending on your specific scenario, is by using the global keyword. This is especially useful when you want to use a global variable inside a function.

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

Here's how:

In this snippet, we declare x as a global variable inside the function foo . This tells Python to look for x in the global scope, not the local one . Now, when you run the function, it will increment the global x by 1 and print 1 .

Similar Error: NameError

An error that's similar to the "local variable referenced before assignment" error is the NameError . This is raised when you try to use a variable or a function name that has not been defined yet.

Running this code will result in a NameError :

In this case, we're trying to print the value of y , but y has not been defined anywhere in the code. Hence, Python raises a NameError . This is similar in that we are trying to use an uninitialized/undefined variable, but the main difference is that we didn't try to initialize y anywhere else in our code.

Variable Scope in Python

Understanding the concept of variable scope can help avoid many common errors in Python, including the main error of interest in this Byte. But what exactly is variable scope?

In Python, variables have two types of scope - global and local. A variable declared inside a function is known as a local variable, while a variable declared outside a function is a global variable.

Consider this example:

In this code, x is a global variable, and y is a local variable. x can be accessed anywhere in the code, but y can only be accessed within my_function . Confusion surrounding this is one of the most common causes for the "variable referenced before assignment" error.

In this Byte, we've taken a look at the "local variable referenced before assignment" error and another similar error, NameError . We also delved into the concept of variable scope in Python, which is an important concept to understand to avoid these errors. If you're seeing one of these errors, check the scope of your variables and make sure they're being assigned before they're being used.

local variable 'result' referenced before assignment python

Monitor with Ping Bot

Reliable monitoring for your app, databases, infrastructure, and the vendors they rely on. Ping Bot is a powerful uptime and performance monitoring tool that helps notify you and resolve issues before they affect your customers.

OpenAI

© 2013- 2024 Stack Abuse. All rights reserved.

Local variable referenced before assignment in Python

avatar

Last updated: Apr 8, 2024 Reading time · 4 min

banner

# Local variable referenced before assignment in Python

The Python "UnboundLocalError: Local variable referenced before assignment" occurs when we reference a local variable before assigning a value to it in a function.

To solve the error, mark the variable as global in the function definition, e.g. global my_var .

unboundlocalerror local variable name referenced before assignment

Here is an example of how the error occurs.

We assign a value to the name variable in the function.

# Mark the variable as global to solve the error

To solve the error, mark the variable as global in your function definition.

mark variable as global

If a variable is assigned a value in a function's body, it is a local variable unless explicitly declared as global .

# Local variables shadow global ones with the same name

You could reference the global name variable from inside the function but if you assign a value to the variable in the function's body, the local variable shadows the global one.

accessing global variables in functions

Accessing the name variable in the function is perfectly fine.

On the other hand, variables declared in a function cannot be accessed from the global scope.

variables declared in function cannot be accessed in global scope

The name variable is declared in the function, so trying to access it from outside causes an error.

Make sure you don't try to access the variable before using the global keyword, otherwise, you'd get the SyntaxError: name 'X' is used prior to global declaration error.

# Returning a value from the function instead

An alternative solution to using the global keyword is to return a value from the function and use the value to reassign the global variable.

return value from the function

We simply return the value that we eventually use to assign to the name global variable.

# Passing the global variable as an argument to the function

You should also consider passing the global variable as an argument to the function.

pass global variable as argument to function

We passed the name global variable as an argument to the function.

If we assign a value to a variable in a function, the variable is assumed to be local unless explicitly declared as global .

# Assigning a value to a local variable from an outer scope

If you have a nested function and are trying to assign a value to the local variables from the outer function, use the nonlocal keyword.

assign value to local variable from outer scope

The nonlocal keyword allows us to work with the local variables of enclosing functions.

Had we not used the nonlocal statement, the call to the print() function would have returned an empty string.

not using nonlocal prints empty string

Printing the message variable on the last line of the function shows an empty string because the inner() function has its own scope.

Changing the value of the variable in the inner scope is not possible unless we use the nonlocal keyword.

Instead, the message variable in the inner function simply shadows the variable with the same name from the outer scope.

# Discussion

As shown in this section of the documentation, when you assign a value to a variable inside a function, the variable:

  • Becomes local to the scope.
  • Shadows any variables from the outer scope that have the same name.

The last line in the example function assigns a value to the name variable, marking it as a local variable and shadowing the name variable from the outer scope.

At the time the print(name) line runs, the name variable is not yet initialized, which causes the error.

The most intuitive way to solve the error is to use the global keyword.

The global keyword is used to indicate to Python that we are actually modifying the value of the name variable from the outer scope.

  • If a variable is only referenced inside a function, it is implicitly global.
  • If a variable is assigned a value inside a function's body, it is assumed to be local, unless explicitly marked as global .

If you want to read more about why this error occurs, check out [this section] ( this section ) of the docs.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • SyntaxError: name 'X' is used prior to global declaration

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

local variable 'result' referenced before assignment python

Explore your training options in 10 minutes Get Started

  • Graduate Stories
  • Partner Spotlights
  • Bootcamp Prep
  • Bootcamp Admissions
  • University Bootcamps
  • Coding Tools
  • Software Engineering
  • Web Development
  • Data Science
  • Tech Guides
  • Tech Resources
  • Career Advice
  • Online Learning
  • Internships
  • Apprenticeships
  • Tech Salaries
  • Associate Degree
  • Bachelor's Degree
  • Master's Degree
  • University Admissions
  • Best Schools
  • Certifications
  • Bootcamp Financing
  • Higher Ed Financing
  • Scholarships
  • Financial Aid
  • Best Coding Bootcamps
  • Best Online Bootcamps
  • Best Web Design Bootcamps
  • Best Data Science Bootcamps
  • Best Technology Sales Bootcamps
  • Best Data Analytics Bootcamps
  • Best Cybersecurity Bootcamps
  • Best Digital Marketing Bootcamps
  • Los Angeles
  • San Francisco
  • Browse All Locations
  • Digital Marketing
  • Machine Learning
  • See All Subjects
  • Bootcamps 101
  • Full-Stack Development
  • Career Changes
  • View all Career Discussions
  • Mobile App Development
  • Cybersecurity
  • Product Management
  • UX/UI Design
  • What is a Coding Bootcamp?
  • Are Coding Bootcamps Worth It?
  • How to Choose a Coding Bootcamp
  • Best Online Coding Bootcamps and Courses
  • Best Free Bootcamps and Coding Training
  • Coding Bootcamp vs. Community College
  • Coding Bootcamp vs. Self-Learning
  • Bootcamps vs. Certifications: Compared
  • What Is a Coding Bootcamp Job Guarantee?
  • How to Pay for Coding Bootcamp
  • Ultimate Guide to Coding Bootcamp Loans
  • Best Coding Bootcamp Scholarships and Grants
  • Education Stipends for Coding Bootcamps
  • Get Your Coding Bootcamp Sponsored by Your Employer
  • GI Bill and Coding Bootcamps
  • Tech Intevriews
  • Our Enterprise Solution
  • Connect With Us
  • Publication
  • Reskill America
  • Partner With Us

Career Karma

  • Resource Center
  • Bachelor’s Degree
  • Master’s Degree

Python local variable referenced before assignment Solution

When you start introducing functions into your code, you’re bound to encounter an UnboundLocalError at some point. This error is raised when you try to use a variable before it has been assigned in the local context .

In this guide, we talk about what this error means and why it is raised. We walk through an example of this error in action to help you understand how you can solve it.

Find your bootcamp match

What is unboundlocalerror: local variable referenced before assignment.

Trying to assign a value to a variable that does not have local scope can result in this error:

Python has a simple rule to determine the scope of a variable. If a variable is assigned in a function , that variable is local. This is because it is assumed that when you define a variable inside a function you only need to access it inside that function.

There are two variable scopes in Python: local and global. Global variables are accessible throughout an entire program; local variables are only accessible within the function in which they are originally defined.

Let’s take a look at how to solve this error.

An Example Scenario

We’re going to write a program that calculates the grade a student has earned in class.

We start by declaring two variables:

These variables store the numerical and letter grades a student has earned, respectively. By default, the value of “letter” is “F”. Next, we write a function that calculates a student’s letter grade based on their numerical grade using an “if” statement :

Finally, we call our function:

This line of code prints out the value returned by the calculate_grade() function to the console. We pass through one parameter into our function: numerical. This is the numerical value of the grade a student has earned.

Let’s run our code and see what happens:

An error has been raised.

The Solution

Our code returns an error because we reference “letter” before we assign it.

We have set the value of “numerical” to 42. Our if statement does not set a value for any grade over 50. This means that when we call our calculate_grade() function, our return statement does not know the value to which we are referring.

We do define “letter” at the start of our program. However, we define it in the global context. Python treats “return letter” as trying to return a local variable called “letter”, not a global variable.

We solve this problem in two ways. First, we can add an else statement to our code. This ensures we declare “letter” before we try to return it:

Let’s try to run our code again:

Our code successfully prints out the student’s grade.

If you are using an “if” statement where you declare a variable, you should make sure there is an “else” statement in place. This will make sure that even if none of your if statements evaluate to True, you can still set a value for the variable with which you are going to work.

Alternatively, we could use the “global” keyword to make our global keyword available in the local context in our calculate_grade() function. However, this approach is likely to lead to more confusing code and other issues. In general, variables should not be declared using “global” unless absolutely necessary . Your first, and main, port of call should always be to make sure that a variable is correctly defined.

In the example above, for instance, we did not check that the variable “letter” was defined in all use cases.

That’s it! We have fixed the local variable error in our code.

The UnboundLocalError: local variable referenced before assignment error is raised when you try to assign a value to a local variable before it has been declared. You can solve this error by ensuring that a local variable is declared before you assign it a value.

Now you’re ready to solve UnboundLocalError Python errors like a professional developer !

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication .

What's Next?

icon_10

Get matched with top bootcamps

Ask a question to our community, take our careers quiz.

James Gallagher

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Apply to top tech training programs in one click

  • Python Course
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

UnboundLocalError Local variable Referenced Before Assignment in Python

Handling errors is an integral part of writing robust and reliable Python code. One common stumbling block that developers often encounter is the “UnboundLocalError” raised within a try-except block. This error can be perplexing for those unfamiliar with its nuances but fear not – in this article, we will delve into the intricacies of the UnboundLocalError and provide a comprehensive guide on how to effectively use try-except statements to resolve it.

What is UnboundLocalError Local variable Referenced Before Assignment in Python?

The UnboundLocalError occurs when a local variable is referenced before it has been assigned a value within a function or method. This error typically surfaces when utilizing try-except blocks to handle exceptions, creating a puzzle for developers trying to comprehend its origins and find a solution.

Why does UnboundLocalError: Local variable Referenced Before Assignment Occur?

below, are the reasons of occurring “Unboundlocalerror: Try Except Statements” in Python :

Variable Assignment Inside Try Block

Reassigning a global variable inside except block.

  • Accessing a Variable Defined Inside an If Block

In the below code, example_function attempts to execute some_operation within a try-except block. If an exception occurs, it prints an error message. However, if no exception occurs, it prints the value of the variable result outside the try block, leading to an UnboundLocalError since result might not be defined if an exception was caught.

In below code , modify_global function attempts to increment the global variable global_var within a try block, but it raises an UnboundLocalError. This error occurs because the function treats global_var as a local variable due to the assignment operation within the try block.

Solution for UnboundLocalError Local variable Referenced Before Assignment

Below, are the approaches to solve “Unboundlocalerror: Try Except Statements”.

Initialize Variables Outside the Try Block

Avoid reassignment of global variables.

In modification to the example_function is correct. Initializing the variable result before the try block ensures that it exists even if an exception occurs within the try block. This helps prevent UnboundLocalError when trying to access result in the print statement outside the try block.

 

Below, code calculates a new value ( local_var ) based on the global variable and then prints both the local and global variables separately. It demonstrates that the global variable is accessed directly without being reassigned within the function.

In conclusion , To fix “UnboundLocalError” related to try-except statements, ensure that variables used within the try block are initialized before the try block starts. This can be achieved by declaring the variables with default values or assigning them None outside the try block. Additionally, when modifying global variables within a try block, use the `global` keyword to explicitly declare them.

Please Login to comment...

Similar reads.

  • Python Programs
  • Python Errors
  • 105 Funny Things to Do to Make Someone Laugh
  • Best PS5 SSDs in 2024: Top Picks for Expanding Your Storage
  • Best Nintendo Switch Controllers in 2024
  • Xbox Game Pass Ultimate: Features, Benefits, and Pricing in 2024
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

How to fix UnboundLocalError: local variable 'x' referenced before assignment in Python

local variable 'result' referenced before assignment python

You could also see this error when you forget to pass the variable as an argument to your function.

How to reproduce this error

How to fix this error.

I hope this tutorial is useful. See you in other tutorials.

Take your skills to the next level ⚡️

Local variable referenced before assignment in Python

The “local variable referenced before assignment” error occurs when you try to use a local variable before it has been assigned a value. This is a general programming concept describing the situation typically arises in situations where you declare a variable within a function but then try to access or modify it before actually assigning a value to it.

In Python, the compiler might throw the exact error: “UnboundLocalError: cannot access local variable ‘x’ where it is not associated with a value”

Here’s an example to illustrate this error:

In this example, you would encounter the above error because you’re trying to print the value of x before it has been assigned a value. To fix this, you should assign a value to x before attempting to access it:

In the corrected version, the local variable x is assigned a value before it’s used, preventing the error.

Keep in mind that Python treats variables inside functions as local unless explicitly stated otherwise using the global keyword (for global variables) or the nonlocal keyword (for variables in nested functions).

If you encounter this error and you’re sure that the variable should have been assigned a value before its use, double-check your code for any logical errors or typos that might be causing the variable to not be assigned properly.

Using the global keyword

If you have a global variable named letter and you try to modify it inside a function without declaring it as global, you will get error.

This is because Python assumes that any variable that is assigned a value inside a function is a local variable, unless you explicitly tell it otherwise.

To fix this error, you can use the global keyword to indicate that you want to use the global variable:

Using nonlocal keyword

The nonlocal keyword is used to work with variables inside nested functions, where the variable should not belong to the inner function. It allows you to modify the value of a non-local variable in the outer scope.

For example, if you have a function outer that defines a variable x , and another function inner inside outer that tries to change the value of x , you need to use the nonlocal keyword to tell Python that you are referring to the x defined in outer , not a new local variable in inner .

Here is an example of how to use the nonlocal keyword:

If you don’t use the nonlocal keyword, Python will create a new local variable x in inner , and the value of x in outer will not be changed:

You might also like

[SOLVED] Local Variable Referenced Before Assignment

local variable referenced before assignment

Python treats variables referenced only inside a function as global variables. Any variable assigned to a function’s body is assumed to be a local variable unless explicitly declared as global.

Why Does This Error Occur?

Unboundlocalerror: local variable referenced before assignment occurs when a variable is used before its created. Python does not have the concept of variable declarations. Hence it searches for the variable whenever used. When not found, it throws the error.

Before we hop into the solutions, let’s have a look at what is the global and local variables.

Local Variable Declarations vs. Global Variable Declarations

Local VariablesGlobal Variables
A variable is declared primarily within a Python function.Global variables are in the global scope, outside a function.
A local variable is created when the function is called and destroyed when the execution is finished.A Variable is created upon execution and exists in memory till the program stops.
Local Variables can only be accessed within their own function.All functions of the program can access global variables.
Local variables are immune to changes in the global scope. Thereby being more secure.Global Variables are less safer from manipulation as they are accessible in the global scope.

[Fixed] typeerror can’t compare datetime.datetime to datetime.date

Local Variable Referenced Before Assignment Error with Explanation

Try these examples yourself using our Online Compiler.

Let’s look at the following function:

Local Variable Referenced Before Assignment Error

Explanation

The variable myVar has been assigned a value twice. Once before the declaration of myFunction and within myFunction itself.

Using Global Variables

Passing the variable as global allows the function to recognize the variable outside the function.

Create Functions that Take in Parameters

Instead of initializing myVar as a global or local variable, it can be passed to the function as a parameter. This removes the need to create a variable in memory.

UnboundLocalError: local variable ‘DISTRO_NAME’

This error may occur when trying to launch the Anaconda Navigator in Linux Systems.

Upon launching Anaconda Navigator, the opening screen freezes and doesn’t proceed to load.

Try and update your Anaconda Navigator with the following command.

If solution one doesn’t work, you have to edit a file located at

After finding and opening the Python file, make the following changes:

In the function on line 159, simply add the line:

DISTRO_NAME = None

Save the file and re-launch Anaconda Navigator.

DJANGO – Local Variable Referenced Before Assignment [Form]

The program takes information from a form filled out by a user. Accordingly, an email is sent using the information.

Upon running you get the following error:

We have created a class myForm that creates instances of Django forms. It extracts the user’s name, email, and message to be sent.

A function GetContact is created to use the information from the Django form and produce an email. It takes one request parameter. Prior to sending the email, the function verifies the validity of the form. Upon True , .get() function is passed to fetch the name, email, and message. Finally, the email sent via the send_mail function

Why does the error occur?

We are initializing form under the if request.method == “POST” condition statement. Using the GET request, our variable form doesn’t get defined.

Local variable Referenced before assignment but it is global

This is a common error that happens when we don’t provide a value to a variable and reference it. This can happen with local variables. Global variables can’t be assigned.

This error message is raised when a variable is referenced before it has been assigned a value within the local scope of a function, even though it is a global variable.

Here’s an example to help illustrate the problem:

In this example, x is a global variable that is defined outside of the function my_func(). However, when we try to print the value of x inside the function, we get a UnboundLocalError with the message “local variable ‘x’ referenced before assignment”.

This is because the += operator implicitly creates a local variable within the function’s scope, which shadows the global variable of the same name. Since we’re trying to access the value of x before it’s been assigned a value within the local scope, the interpreter raises an error.

To fix this, you can use the global keyword to explicitly refer to the global variable within the function’s scope:

However, in the above example, the global keyword tells Python that we want to modify the value of the global variable x, rather than creating a new local variable. This allows us to access and modify the global variable within the function’s scope, without causing any errors.

Local variable ‘version’ referenced before assignment ubuntu-drivers

This error occurs with Ubuntu version drivers. To solve this error, you can re-specify the version information and give a split as 2 –

Here, p_name means package name.

With the help of the threading module, you can avoid using global variables in multi-threading. Make sure you lock and release your threads correctly to avoid the race condition.

When a variable that is created locally is called before assigning, it results in Unbound Local Error in Python. The interpreter can’t track the variable.

Therefore, we have examined the local variable referenced before the assignment Exception in Python. The differences between a local and global variable declaration have been explained, and multiple solutions regarding the issue have been provided.

Trending Python Articles

[Fixed] nameerror: name Unicode is not defined

How to Fix Local Variable Referenced Before Assignment Error in Python

How to Fix Local Variable Referenced Before Assignment Error in Python

Table of Contents

Fixing local variable referenced before assignment error.

In Python , when you try to reference a variable that hasn't yet been given a value (assigned), it will throw an error.

That error will look like this:

In this post, we'll see examples of what causes this and how to fix it.

Let's begin by looking at an example of this error:

If you run this code, you'll get

The issue is that in this line:

We are defining a local variable called value and then trying to use it before it has been assigned a value, instead of using the variable that we defined in the first line.

If we want to refer the variable that was defined in the first line, we can make use of the global keyword.

The global keyword is used to refer to a variable that is defined outside of a function.

Let's look at how using global can fix our issue here:

Global variables have global scope, so you can referenced them anywhere in your code, thus avoiding the error.

If you run this code, you'll get this output:

In this post, we learned at how to avoid the local variable referenced before assignment error in Python.

The error stems from trying to refer to a variable without an assigned value, so either make use of a global variable using the global keyword, or assign the variable a value before using it.

Thanks for reading!

local variable 'result' referenced before assignment python

  • Privacy Policy
  • Terms of Service

Adventures in Machine Learning

4 ways to fix local variable referenced before assignment error in python, resolving the local variable referenced before assignment error in python.

Python is one of the world’s most popular programming languages due to its simplicity, readability, and versatility. Despite its many advantages, when coding in Python, one may encounter various errors, with the most common being the “local variable referenced before assignment” error.

Even the most experienced Python developers have encountered this error at some point in their programming career. In this article, we will look at four effective strategies for resolving the local variable referenced before assignment error in Python.

Strategy 1: Assigning a Value before Referencing

The first strategy is to assign a value to a variable before referencing it. The error occurs when the variable is referenced before it is assigned a value.

This problem can be avoided by initializing the variable before referencing it. For example, let us consider the snippet below:

In the snippet above, the variables x and y are not assigned values before they are referenced in the print statement. Therefore, we will get a local variable “referenced before assignment” error.

To resolve this error, we must initialize the variables before referencing them. We can avoid this error by assigning a value to x and y before they are referenced, as shown below:

Strategy 2: Using the Global Keyword

In Python, variables declared inside a function are considered local variables. Thus, they are separate from other variables declared outside of the function.

If we want to use a variable outside of the function, we must use the global keyword. Using the global keyword tells Python that you want to use the variable that was defined globally, not locally.

For example:

In the code snippet above, the global keyword tells Python to use the variable x defined outside of the function rather than a local variable named x . Thus, Python will output 30.

Strategy 3: Adding Input Parameters for Functions

Another way to avoid the local variable referenced before assignment error is by adding input parameters to functions.

In the code snippet above, x and y are variables that are passed into the add_numbers function as arguments.

This approach allows us to avoid the local variable referenced before assignment error because the variables are being passed into the function as input parameters.

Strategy 4: Initializing Variables before Loops or Conditionals

Finally, it’s also a good practice to initialize the variables before loops or conditionals.

If you are defining a variable within a loop, you must initialize it before the loop starts. This way, the variable already exists, and we can update the value inside the loop.

In the code snippet above, the variable sum has been initialized with the value of 0 before the loop runs. Thus, we can update and use the variable inside the loop.

In conclusion, the “local variable referenced before assignment” error is a common issue in Python. However, with the strategies discussed in this article, you can avoid the error and write clean Python code.

Remember to initialize your variables, use the global keyword, add input parameters in functions, and initialize variables before loops or conditionals. By following these techniques, your Python code will be error-free and much easier to manage.

In essence, this article has provided four key strategies for resolving the “local variable referenced before assignment” error that is common in Python. These strategies include initializing variables before referencing, using the global keyword, adding input parameters to functions, and initializing variables before loops or conditionals.

These techniques help to ensure clean code that is free from errors. By implementing these strategies, developers can improve their code quality and avoid time-wasting errors that can occur in their work.

Popular Posts

Efficient techniques for working with dictionaries in python, crucial rules and best practices for python identifier naming, mastering sql programming: a comprehensive guide.

  • Terms & Conditions
  • Privacy Policy

HatchJS Logo

HatchJS.com

Cracking the Shell of Mystery

Local Variable Referenced Before Assignment in Python: What It Is and How to Fix It

Avatar

Local Variable Referenced Before Assignment in Python

One of the most common errors in Python is to reference a local variable before it has been assigned a value. This can cause your program to crash or produce unexpected results.

In this article, we’ll take a look at what happens when you reference a local variable before assignment, and how you can avoid this error. We’ll also discuss some of the reasons why this error occurs, and how you can debug it if it happens in your own code.

What is a local variable?

A local variable is a variable that is declared within a function or a block of code. Local variables are only accessible within the function or block of code in which they are declared.

What happens when you reference a local variable before assignment?

When you reference a local variable before it has been assigned a value, Python will raise a `NameError` exception. This exception tells you that the variable you are trying to reference does not exist.

How can you avoid this error?

There are a few ways to avoid this error.

  • Always assign a value to a local variable before you reference it. This is the simplest and most effective way to avoid this error.
  • Use the `global` keyword to declare a variable as global. This will make the variable accessible from outside of the function or block of code in which it is declared.
  • Use the `nonlocal` keyword to declare a variable as nonlocal. This will make the variable accessible from the enclosing function or block of code.

Why does this error occur?

There are a few reasons why this error might occur.

  • You might have accidentally misspelled the name of the variable. Make sure that you are spelling the variable name correctly.
  • You might have forgotten to assign a value to the variable. Make sure that you assign a value to the variable before you try to reference it.
  • You might be trying to reference a variable that is defined in a different scope. If you are trying to reference a variable that is defined in a different scope, you will need to use the `global` or `nonlocal` keyword.

How can you debug this error?

If you get a `NameError` exception when you are trying to reference a local variable, there are a few things you can do to debug the error.

  • Check the spelling of the variable name. Make sure that you are spelling the variable name correctly.
  • Check to see if you have assigned a value to the variable. Make sure that you have assigned a value to the variable before you try to reference it.

|—|—|—| | Variable name | Line number | Error message | | x | 10 | UnboundLocalError: local variable ‘x’ referenced before assignment | | y | 15 | UnboundLocalError: local variable ‘y’ referenced before assignment | | z | 20 | UnboundLocalError: local variable ‘z’ referenced before assignment |

In Python, a local variable is a variable that is declared inside a function or a block of code. Local variables are not accessible outside the function or block of code in which they are declared. This means that you cannot reference a local variable from outside the function or block of code in which it is declared.

However, it is possible to reference a local variable before it is assigned a value. This is an error in Python, and will cause a `NameError` exception to be raised.

In this tutorial, we will take a look at what a local variable referenced before assignment is, why it is an error, and how to avoid this error.

What is a local variable referenced before assignment in Python?

A local variable referenced before assignment is a local variable that is used in a statement before it is assigned a value. For example, the following code will raise a `NameError` exception:

python def foo(): This will raise a NameError exception print(x)

x = 10 foo()

The reason for this error is that the variable `x` is not defined when the `foo()` function is called. This is because the `x` variable is declared inside the `foo()` function, and it is not accessible outside of the function.

Why is it an error to reference a local variable before assignment in Python?

The reason why it is an error to reference a local variable before assignment in Python is because the variable does not exist yet. When a variable is declared, it is not created until it is assigned a value. This means that if you try to reference a variable before it is assigned a value, Python will not be able to find it.

How to avoid the error of referencing a local variable before assignment in Python

There are a few ways to avoid the error of referencing a local variable before assignment in Python.

One way is to assign a value to the variable before it is referenced. For example, the following code will not raise a `NameError` exception:

python def foo(): x = 10 print(x)

Another way to avoid the error is to use the `global` keyword. The `global` keyword tells Python that the variable is a global variable, and it can be accessed from anywhere in the program. For example, the following code will not raise a `NameError` exception:

python def foo(): global x x = 10 print(x)

Finally, you can also use the `nonlocal` keyword. The `nonlocal` keyword tells Python that the variable is a nonlocal variable, and it can be accessed from the current function and any enclosing functions. For example, the following code will not raise a `NameError` exception:

python def foo(): x = 10 def bar(): nonlocal x x = 20 bar() print(x)

it is an error to reference a local variable before assignment in Python. This is because the variable does not exist yet. There are a few ways to avoid this error, such as assigning a value to the variable before it is referenced, using the `global` keyword, or using the `nonlocal` keyword.

A local variable is a variable that is declared within a function or a block of code. Local variables are only accessible within the scope in which they are declared. This means that they cannot be accessed outside of the function or block of code in which they are declared.

When you try to reference a local variable before it has been assigned a value, Python will raise a `NameError` exception. This is because Python does not know what value to assign to the variable, since it has not been assigned a value yet.

How to fix the error of referencing a local variable before assignment in Python?

There are two ways to fix the error of referencing a local variable before assignment in Python:

1. Assign a value to the variable before it is referenced.

This is the simplest way to fix the error. Simply assign a value to the variable before you try to reference it. For example:

2. Use the `global` keyword to declare the variable as a global variable.

If you need to reference a local variable before it has been assigned a value, you can use the `global` keyword to declare the variable as a global variable. This will make the variable accessible from outside of the function or block of code in which it is declared. For example:

Examples of referencing a local variable before assignment in Python

The following code raises a `NameError` exception:

This is because the variable `x` is not assigned a value before it is referenced in the `print()` statement.

The following code fixes the error by assigning a value to the variable before it is referenced:

The following code also fixes the error by declaring the variable `x` as a global variable:

In this tutorial, you learned what a local variable referenced before assignment is and how to fix the error in Python. You also saw two examples of referencing a local variable before assignment and how to fix the error.

Q: What does it mean when a local variable is referenced before assignment in Python?

A: A local variable is referenced before assignment when a variable is used in an expression before it has been assigned a value. This can cause errors, as the variable may not have been initialized and may contain an unexpected value.

Q: How can I avoid referencing a local variable before assignment in Python?

A: There are a few ways to avoid referencing a local variable before assignment in Python.

  • Use the `None` keyword. When you declare a variable, you can initialize it to the `None` value. This tells the interpreter that the variable has not been assigned a value yet.
  • Use the `assert` statement. You can use the `assert` statement to check if a variable has been assigned a value before using it. If the variable has not been assigned a value, the `assert` statement will raise an error.
  • Use the `del` statement. You can use the `del` statement to delete a variable. This will remove the variable from the local scope, so it cannot be referenced again.

Q: What are the consequences of referencing a local variable before assignment in Python?

A: If you reference a local variable before assignment in Python, the following consequences may occur:

  • The variable may contain an unexpected value.
  • The program may crash.
  • The program may produce incorrect results.

Q: How can I debug a Python program that is referencing a local variable before assignment?

A: There are a few ways to debug a Python program that is referencing a local variable before assignment.

  • Use a debugger. A debugger allows you to step through your program line by line, so you can see where the local variable is being referenced.
  • Use the `print()` function. You can use the `print()` function to print the value of the local variable at different points in your program. This can help you track down where the variable is being initialized.
  • Use the `assert` statement. You can use the `assert` statement to check if the local variable has been assigned a value before using it. If the variable has not been assigned a value, the `assert` statement will raise an error.

Q: What are some best practices for avoiding referencing local variables before assignment in Python?

A: Here are some best practices for avoiding referencing local variables before assignment in Python:

  • Initialize local variables to a known value. This will prevent the variable from containing an unexpected value.
  • Use the `None` keyword to initialize local variables. This will tell the interpreter that the variable has not been assigned a value yet.
  • Use the `assert` statement to check if local variables have been assigned a value. This will help you catch errors early.

We hope that this blog post has been helpful. If you have any other questions about Python, please feel free to contact us.

Author Profile

Marcus Greenwood

Latest entries

  • December 26, 2023 Error Fixing User: Anonymous is not authorized to perform: execute-api:invoke on resource: How to fix this error
  • December 26, 2023 How To Guides Valid Intents Must Be Provided for the Client: Why It’s Important and How to Do It
  • December 26, 2023 Error Fixing How to Fix the The Root Filesystem Requires a Manual fsck Error
  • December 26, 2023 Troubleshooting How to Fix the `sed unterminated s` Command

Similar Posts

No suitable method found to override: what it means and how to fix it.

No Suitable Method Found to Override: What It Means and How to Fix It Have you ever tried to override a method in Java, only to get an error message saying “no suitable method found to override”? This is a common error, and it can be frustrating to figure out what’s going wrong. In this…

/var/run/libvirt/libvirt-sock’ no such file or directory: How to fix

Have you ever encountered the error message “/var/run/libvirt/libvirt-sock: no such file or directory”? If so, you’re not alone. This error is a common one, and it can be caused by a variety of factors. In this article, we’ll take a closer look at this error message, and we’ll discuss some of the things you can…

Can You Put LED Bulbs in Incandescent Fixtures?

Can You Put LED Bulbs in Incandescent Fixtures? Incandescent light bulbs have been the standard for decades, but they’re quickly being replaced by more energy-efficient LED bulbs. But what if you have an old incandescent fixture? Can you just put an LED bulb in it? The answer is: it depends. Some incandescent fixtures are designed…

Software Update Command Not Found: How to Fix

Softwareupdate Command Not Found: A Guide to Fixing the Error Have you ever tried to run the softwareupdate command on your Mac, only to be greeted with the error message “softwareupdate command not found”? If so, you’re not alone. This is a common problem that can be caused by a variety of factors. In this…

Kubectl invalid apiversion client.authentication.k8s.io/v1alpha1: How to fix

Kubernetes kubectl invalid apiversion client.authentication.k8s.io/v1alpha1 Kubernetes is a powerful container orchestration system that allows you to deploy, manage, and scale containerized applications. One of the most common ways to interact with Kubernetes is using the kubectl command-line tool. However, you may encounter an error message like “invalid apiversion client.authentication.k8s.io/v1alpha1” when using kubectl. This error message…

How to Fix Uneven Drywall Seams: A Step-by-Step Guide

How to Fix Uneven Drywall Seams Drywall is a versatile and affordable material that can be used to create smooth, attractive walls in any room. However, even the most experienced drywallers can sometimes end up with uneven seams. If you’re not happy with the way your drywall seams look, don’t despair! There are a few…

How to Solve Error - Local Variable Referenced Before Assignment in Python

  • Python How-To's
  • How to Solve Error - Local Variable …

Check the Variable Scope to Fix the local variable referenced before assignment Error in Python

Initialize the variable before use to fix the local variable referenced before assignment error in python, use conditional assignment to fix the local variable referenced before assignment error in python.

How to Solve Error - Local Variable Referenced Before Assignment in Python

This article delves into various strategies to resolve the common local variable referenced before assignment error. By exploring methods such as checking variable scope, initializing variables before use, conditional assignments, and more, we aim to equip both novice and seasoned programmers with practical solutions.

Each method is dissected with examples, demonstrating how subtle changes in code can prevent this frequent error, enhancing the robustness and readability of your Python projects.

The local variable referenced before assignment occurs when some variable is referenced before assignment within a function’s body. The error usually occurs when the code is trying to access the global variable.

The primary purpose of managing variable scope is to ensure that variables are accessible where they are needed while maintaining code modularity and preventing unexpected modifications to global variables.

We can declare the variable as global using the global keyword in Python. Once the variable is declared global, the program can access the variable within a function, and no error will occur.

The below example code demonstrates the code scenario where the program will end up with the local variable referenced before assignment error.

In this example, my_var is a global variable. Inside update_var , we attempt to modify it without declaring its scope, leading to the Local Variable Referenced Before Assignment error.

We need to declare the my_var variable as global using the global keyword to resolve this error. The below example code demonstrates how the error can be resolved using the global keyword in the above code scenario.

In the corrected code, we use the global keyword to inform Python that my_var references the global variable.

When we first print my_var , it displays the original value from the global scope.

After assigning a new value to my_var , it updates the global variable, not a local one. This way, we effectively tell Python the scope of our variable, thus avoiding any conflicts between local and global variables with the same name.

python local variable referenced before assignment - output 1

Ensure that the variable is initialized with some value before using it. This can be done by assigning a default value to the variable at the beginning of the function or code block.

The main purpose of initializing variables before use is to ensure that they have a defined state before any operations are performed on them. This practice is not only crucial for avoiding the aforementioned error but also promotes writing clear and predictable code, which is essential in both simple scripts and complex applications.

In this example, the variable total is used in the function calculate_total without prior initialization, leading to the Local Variable Referenced Before Assignment error. The below example code demonstrates how the error can be resolved in the above code scenario.

In our corrected code, we initialize the variable total with 0 before using it in the loop. This ensures that when we start adding item values to total , it already has a defined state (in this case, 0).

This initialization is crucial because it provides a starting point for accumulation within the loop. Without this step, Python does not know the initial state of total , leading to the error.

python local variable referenced before assignment - output 2

Conditional assignment allows variables to be assigned values based on certain conditions or logical expressions. This method is particularly useful when a variable’s value depends on certain prerequisites or states, ensuring that a variable is always initialized before it’s used, thereby avoiding the common error.

In this example, message is only assigned within the if and elif blocks. If neither condition is met (as with guest ), the variable message remains uninitialized, leading to the Local Variable Referenced Before Assignment error when trying to print it.

The below example code demonstrates how the error can be resolved in the above code scenario.

In the revised code, we’ve included an else statement as part of our conditional logic. This guarantees that no matter what value user_type holds, the variable message will be assigned some value before it is used in the print function.

This conditional assignment ensures that the message is always initialized, thereby eliminating the possibility of encountering the Local Variable Referenced Before Assignment error.

python local variable referenced before assignment - output 3

Throughout this article, we have explored multiple approaches to address the Local Variable Referenced Before Assignment error in Python. From the nuances of variable scope to the effectiveness of initializations and conditional assignments, these strategies are instrumental in developing error-free code.

The key takeaway is the importance of understanding variable scope and initialization in Python. By applying these methods appropriately, programmers can not only resolve this specific error but also enhance the overall quality and maintainability of their code, making their programming journey smoother and more rewarding.

The Research Scientist Pod

Python UnboundLocalError: local variable referenced before assignment

by Suf | Programming , Python , Tips

If you try to reference a local variable before assigning a value to it within the body of a function, you will encounter the UnboundLocalError: local variable referenced before assignment.

The preferable way to solve this error is to pass parameters to your function, for example:

Alternatively, you can declare the variable as global to access it while inside a function. For example,

This tutorial will go through the error in detail and how to solve it with code examples .

Table of contents

What is scope in python, unboundlocalerror: local variable referenced before assignment, solution #1: passing parameters to the function, solution #2: use global keyword, solution #1: include else statement, solution #2: use global keyword.

Scope refers to a variable being only available inside the region where it was created. A variable created inside a function belongs to the local scope of that function, and we can only use that variable inside that function.

A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available within any scope, global and local.

UnboundLocalError occurs when we try to modify a variable defined as local before creating it. If we only need to read a variable within a function, we can do so without using the global keyword. Consider the following example that demonstrates a variable var created with global scope and accessed from test_func :

If we try to assign a value to var within test_func , the Python interpreter will raise the UnboundLocalError:

This error occurs because when we make an assignment to a variable in a scope, that variable becomes local to that scope and overrides any variable with the same name in the global or outer scope.

var +=1 is similar to var = var + 1 , therefore the Python interpreter should first read var , perform the addition and assign the value back to var .

var is a variable local to test_func , so the variable is read or referenced before we have assigned it. As a result, the Python interpreter raises the UnboundLocalError.

Example #1: Accessing a Local Variable

Let’s look at an example where we define a global variable number. We will use the increment_func to increase the numerical value of number by 1.

Let’s run the code to see what happens:

The error occurs because we tried to read a local variable before assigning a value to it.

We can solve this error by passing a parameter to increment_func . This solution is the preferred approach. Typically Python developers avoid declaring global variables unless they are necessary. Let’s look at the revised code:

We have assigned a value to number and passed it to the increment_func , which will resolve the UnboundLocalError. Let’s run the code to see the result:

We successfully printed the value to the console.

We also can solve this error by using the global keyword. The global statement tells the Python interpreter that inside increment_func , the variable number is a global variable even if we assign to it in increment_func . Let’s look at the revised code:

Let’s run the code to see the result:

Example #2: Function with if-elif statements

Let’s look at an example where we collect a score from a player of a game to rank their level of expertise. The variable we will use is called score and the calculate_level function takes in score as a parameter and returns a string containing the player’s level .

In the above code, we have a series of if-elif statements for assigning a string to the level variable. Let’s run the code to see what happens:

The error occurs because we input a score equal to 40 . The conditional statements in the function do not account for a value below 55 , therefore when we call the calculate_level function, Python will attempt to return level without any value assigned to it.

We can solve this error by completing the set of conditions with an else statement. The else statement will provide an assignment to level for all scores lower than 55 . Let’s look at the revised code:

In the above code, all scores below 55 are given the beginner level. Let’s run the code to see what happens:

We can also create a global variable level and then use the global keyword inside calculate_level . Using the global keyword will ensure that the variable is available in the local scope of the calculate_level function. Let’s look at the revised code.

In the above code, we put the global statement inside the function and at the beginning. Note that the “default” value of level is beginner and we do not include the else statement in the function. Let’s run the code to see the result:

Congratulations on reading to the end of this tutorial! The UnboundLocalError: local variable referenced before assignment occurs when you try to reference a local variable before assigning a value to it. Preferably, you can solve this error by passing parameters to your function. Alternatively, you can use the global keyword.

If you have if-elif statements in your code where you assign a value to a local variable and do not account for all outcomes, you may encounter this error. In which case, you must include an else statement to account for the missing outcome.

For further reading on Python code blocks and structure, go to the article: How to Solve Python IndentationError: unindent does not match any outer indentation level .

Go to the  online courses page on Python  to learn more about Python for data science and machine learning.

Have fun and happy researching!

Share this:

  • Click to share on Facebook (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Telegram (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on Tumblr (Opens in new window)

w3docs logo

  • Password Generator
  • HTML Editor
  • HTML Encoder
  • JSON Beautifier
  • CSS Beautifier
  • Markdown Convertor
  • Find the Closest Tailwind CSS Color
  • Phrase encrypt / decrypt
  • Browser Feature Detection
  • Number convertor
  • CSS Maker text shadow
  • CSS Maker Text Rotation
  • CSS Maker Out Line
  • CSS Maker RGB Shadow
  • CSS Maker Transform
  • CSS Maker Font Face
  • Color Picker
  • Colors CMYK
  • Color mixer
  • Color Converter
  • Color Contrast Analyzer
  • Color Gradient
  • String Length Calculator
  • MD5 Hash Generator
  • Sha256 Hash Generator
  • String Reverse
  • URL Encoder
  • URL Decoder
  • Base 64 Encoder
  • Base 64 Decoder
  • Extra Spaces Remover
  • String to Lowercase
  • String to Uppercase
  • Word Count Calculator
  • Empty Lines Remover
  • HTML Tags Remover
  • Binary to Hex
  • Hex to Binary
  • Rot13 Transform on a String
  • String to Binary
  • Duplicate Lines Remover

Python 3: UnboundLocalError: local variable referenced before assignment

This error occurs when you are trying to access a variable before it has been assigned a value. Here is an example of a code snippet that would raise this error:

Watch a video course Python - The Practical Guide

The error message will be:

In this example, the variable x is being accessed before it is assigned a value, which is causing the error. To fix this, you can either move the assignment of the variable x before the print statement, or give it an initial value before the print statement.

Both will work without any error.

Related Resources

  • Using global variables in a function
  • "Least Astonishment" and the Mutable Default Argument
  • Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?
  • HTML Basics
  • Javascript Basics
  • TypeScript Basics
  • React Basics
  • Angular Basics
  • Sass Basics
  • Vue.js Basics
  • Python Basics
  • Java Basics
  • NodeJS Basics

Local variable referenced before assignment in Python

In Python, while working with functions, you can encounter various types of errors. A common error when working with the functions is “ Local variable referenced before assignment ”. The stated error occurs when a local variable is referenced before being assigned any value.

This write-up will provide the possible reasons and the appropriate solutions to the error “Local variable referenced before assignment” with practical examples. The following aspects are discussed in this write-up in detail:

Reason: Reference a Local Variable

Solution 1: mark the variable globally, solution 2: using function parameter value, solution 3: using nonlocal keyword.

The main reason for the “ local variable referenced before assignment ” error in Python is using a variable that does not have local scope. This also means referencing a local variable without assigning it a value in a function.

The variable initialized inside the function will only be accessed inside the function, and these variables are known as local variables. To use variables in the entire program, variables must be initialized globally. The below example illustrates how the “ UnboundLocalError ” occurs in Python.

local variable 'result' referenced before assignment python

In the above snippet, the “ Student ” variable is not marked as global, so when it is accessed inside the function, the Python interpreter returns an error.

Note: We can access the outer variable inside the function, but when the new value is assigned to a variable, the “UnboundLocalError” appears on the screen.

To solve this error, we must mark the “ Student ” variable as a global variable using the keyword “ global ” inside the function.

Within the function, we can assign a new value to the student variable without any error. Let’s have a look at the below snippet for a detailed understanding:

In the above code, the local variable is marked as a “ global ” variable inside the function. We can easily reference the variable before assigning the variable in the program.

local variable 'result' referenced before assignment python

The above snippet proves that the global keyword resolves the “unboundLocalError”.

Passing a value as an argument to the function will also resolve the stated error. The function accepts the variable as an argument and uses the argument value inside the function. Let’s have a look at the given below code block for a better understanding:

In the above code, the variable is referenced before assigning the value inside the user-defined function. The program executes successfully without any errors because the variable is passed as a parameter value of the function.

local variable 'result' referenced before assignment python

The above output shows the value of the function when the function is accessed in the program without any “ Local Variable referenced ” error.

The “ nonlocal ” keyword is utilized in the program to assign a new value to a local variable of function in the nested function. Here is an example of code:

In the above code, the keyword “ nonlocal ” is used to mark the local variable of the outer function as nonlocal. After making the variable nonlocal, we can reference it before assigning a value without any error.

local variable 'result' referenced before assignment python

The above output shows the value of the inner function without any “ local variable referenced ” error in a program.

The “ Local variable referenced before assignment ” appears in Python due to assigning a value to a variable that does not have a local scope. To fix this error, the global keyword, return statement, and nonlocal nested function is used in Python script. The global keywords are used with variables to make it able to access inside and outside the function. The return statement is also used to return the variable’s new value back to function and display the result on the screen. This Python guide presented a detailed overview of the reason and solutions for the error “Local variable referenced before assignment” in Python.

Joseph

Get the Reddit app

Subreddit for posting questions and asking for general advice about your python code.

Local variable referenced before assignment?

This is a piece of code i made for a project to mimic an ATM like machine, this is just the start of it (inputting the pin and accessing balance and other things) . and im wondering why it all works until i input the wrong integer for the pin, thats when it gives me 'UnboundLocalError: local variable 'attempts' referenced before assignment' any ideas?

pin = 4882 import time, random, sys attempts = 5 #def start is basically the log-on to access the rest of the ATM, if you don't know the pin you're stuck here def start(): print("Hello! Please input your card")    time.sleep(4)    user_try = int(input("Thank you! Please input your pin: ")) if user_try == pin: print("Card info correct") elif user_try != pin: attempts = attempts-1 print("Sorry, That pin wasn't right. you have",attempts,"more attempts") if attempts == 0: print("Sorry you've ran out of attempts to access this account") sys.exit time.sleep(1) if user_try == pin: print("Card info correct") start()      

edit: absolutely butchered this, actual code is in the first reply

By continuing, you agree to our User Agreement and acknowledge that you understand the Privacy Policy .

Enter the 6-digit code from your authenticator app

You’ve set up two-factor authentication for this account.

Enter a 6-digit backup code

Create your username and password.

Reddit is anonymous, so your username is what you’ll go by here. Choose wisely—because once you get a name, you can’t change it.

Reset your password

Enter your email address or username and we’ll send you a link to reset your password

Check your inbox

An email with a link to reset your password was sent to the email address associated with your account

Choose a Reddit account to continue

  • Python »
  • 3.9.20 Documentation »
  • The Python Standard Library »
  • Generic Operating System Services »

os — Miscellaneous operating system interfaces ¶

Source code: Lib/os.py

This module provides a portable way of using operating system dependent functionality. If you just want to read or write a file see open() , if you want to manipulate paths, see the os.path module, and if you want to read all the lines in all the files on the command line see the fileinput module. For creating temporary files and directories see the tempfile module, and for high-level file and directory handling see the shutil module.

Notes on the availability of these functions:

The design of all built-in operating system dependent modules of Python is such that as long as the same functionality is available, it uses the same interface; for example, the function os.stat(path) returns stat information about path in the same format (which happens to have originated with the POSIX interface).

Extensions peculiar to a particular operating system are also available through the os module, but using them is of course a threat to portability.

All functions accepting path or file names accept both bytes and string objects, and result in an object of the same type, if a path or file name is returned.

On VxWorks, os.fork, os.execv and os.spawn*p* are not supported.

All functions in this module raise OSError (or subclasses thereof) in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.

An alias for the built-in OSError exception.

The name of the operating system dependent module imported. The following names have currently been registered: 'posix' , 'nt' , 'java' .

Ayrıca bkz.

sys.platform has a finer granularity. os.uname() gives system-dependent version information.

The platform module provides detailed checks for the system’s identity.

File Names, Command Line Arguments, and Environment Variables ¶

In Python, file names, command line arguments, and environment variables are represented using the string type. On some systems, decoding these strings to and from bytes is necessary before passing them to the operating system. Python uses the file system encoding to perform this conversion (see sys.getfilesystemencoding() ).

3.1 sürümünde değişti: On some systems, conversion using the file system encoding may fail. In this case, Python uses the surrogateescape encoding error handler , which means that undecodable bytes are replaced by a Unicode character U+DCxx on decoding, and these are again translated to the original byte on encoding.

The file system encoding must guarantee to successfully decode all bytes below 128. If the file system encoding fails to provide this guarantee, API functions may raise UnicodeErrors.

Process Parameters ¶

These functions and data items provide information and operate on the current process and user.

Return the filename corresponding to the controlling terminal of the process.

Availability : Unix.

A mapping object where keys and values are strings that represent the process environment. For example, environ['HOME'] is the pathname of your home directory (on some platforms), and is equivalent to getenv("HOME") in C.

This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py . Changes to the environment made after this time are not reflected in os.environ , except for changes made by modifying os.environ directly.

This mapping may be used to modify the environment as well as query the environment. putenv() will be called automatically when the mapping is modified.

On Unix, keys and values use sys.getfilesystemencoding() and 'surrogateescape' error handler. Use environb if you would like to use a different encoding.

Calling putenv() directly does not change os.environ , so it’s better to modify os.environ .

On some platforms, including FreeBSD and macOS, setting environ may cause memory leaks. Refer to the system documentation for putenv() .

You can delete items in this mapping to unset environment variables. unsetenv() will be called automatically when an item is deleted from os.environ , and when one of the pop() or clear() methods is called.

3.9 sürümünde değişti: Updated to support PEP 584 ’s merge ( | ) and update ( |= ) operators.

Bytes version of environ : a mapping object where both keys and values are bytes objects representing the process environment. environ and environb are synchronized (modifying environb updates environ , and vice versa).

environb is only available if supports_bytes_environ is True .

3.2 sürümüyle geldi.

These functions are described in Files and Directories .

Encode path-like filename to the filesystem encoding with 'surrogateescape' error handler, or 'strict' on Windows; return bytes unchanged.

fsdecode() is the reverse function.

3.6 sürümünde değişti: Support added to accept objects implementing the os.PathLike interface.

Decode the path-like filename from the filesystem encoding with 'surrogateescape' error handler, or 'strict' on Windows; return str unchanged.

fsencode() is the reverse function.

Return the file system representation of the path.

If str or bytes is passed in, it is returned unchanged. Otherwise __fspath__() is called and its value is returned as long as it is a str or bytes object. In all other cases, TypeError is raised.

3.6 sürümüyle geldi.

An abstract base class for objects representing a file system path, e.g. pathlib.PurePath .

Return the file system path representation of the object.

The method should only return a str or bytes object, with the preference being for str .

Return the value of the environment variable key if it exists, or default if it doesn’t. key , default and the result are str. Note that since getenv() uses os.environ , the mapping of getenv() is similarly also captured on import, and the function may not reflect future environment changes.

On Unix, keys and values are decoded with sys.getfilesystemencoding() and 'surrogateescape' error handler. Use os.getenvb() if you would like to use a different encoding.

Availability : most flavors of Unix, Windows.

Return the value of the environment variable key if it exists, or default if it doesn’t. key , default and the result are bytes. Note that since getenvb() uses os.environb , the mapping of getenvb() is similarly also captured on import, and the function may not reflect future environment changes.

getenvb() is only available if supports_bytes_environ is True .

Availability : most flavors of Unix.

Returns the list of directories that will be searched for a named executable, similar to a shell, when launching a process. env , when specified, should be an environment variable dictionary to lookup the PATH in. By default, when env is None , environ is used.

Return the effective group id of the current process. This corresponds to the “set id” bit on the file being executed in the current process.

Return the current process’s effective user id.

Return the real group id of the current process.

Return list of group ids that user belongs to. If group is not in the list, it is included; typically, group is specified as the group ID field from the password record for user , because that group ID will otherwise be potentially omitted.

3.3 sürümüyle geldi.

Return list of supplemental group ids associated with the current process.

On macOS, getgroups() behavior differs somewhat from other Unix platforms. If the Python interpreter was built with a deployment target of 10.5 or earlier, getgroups() returns the list of effective group ids associated with the current user process; this list is limited to a system-defined number of entries, typically 16, and may be modified by calls to setgroups() if suitably privileged. If built with a deployment target greater than 10.5 , getgroups() returns the current group access list for the user associated with the effective user id of the process; the group access list may change over the lifetime of the process, it is not affected by calls to setgroups() , and its length is not limited to 16. The deployment target value, MACOSX_DEPLOYMENT_TARGET , can be obtained with sysconfig.get_config_var() .

Return the name of the user logged in on the controlling terminal of the process. For most purposes, it is more useful to use getpass.getuser() since the latter checks the environment variables LOGNAME or USERNAME to find out who the user is, and falls back to pwd.getpwuid(os.getuid())[0] to get the login name of the current real user id.

Availability : Unix, Windows.

Return the process group id of the process with process id pid . If pid is 0, the process group id of the current process is returned.

Return the id of the current process group.

Return the current process id.

Return the parent’s process id. When the parent process has exited, on Unix the id returned is the one of the init process (1), on Windows it is still the same id, which may be already reused by another process.

3.2 sürümünde değişti: Added support for Windows.

Get program scheduling priority. The value which is one of PRIO_PROCESS , PRIO_PGRP , or PRIO_USER , and who is interpreted relative to which (a process identifier for PRIO_PROCESS , process group identifier for PRIO_PGRP , and a user ID for PRIO_USER ). A zero value for who denotes (respectively) the calling process, the process group of the calling process, or the real user ID of the calling process.

Parameters for the getpriority() and setpriority() functions.

Return a tuple (ruid, euid, suid) denoting the current process’s real, effective, and saved user ids.

Return a tuple (rgid, egid, sgid) denoting the current process’s real, effective, and saved group ids.

Return the current process’s real user id.

Call the system initgroups() to initialize the group access list with all of the groups of which the specified username is a member, plus the specified group id.

Set the environment variable named key to the string value . Such changes to the environment affect subprocesses started with os.system() , popen() or fork() and execv() .

Assignments to items in os.environ are automatically translated into corresponding calls to putenv() ; however, calls to putenv() don’t update os.environ , so it is actually preferable to assign to items of os.environ . This also applies to getenv() and getenvb() , which respectively use os.environ and os.environb in their implementations.

Raises an auditing event os.putenv with arguments key , value .

3.9 sürümünde değişti: The function is now always available.

Set the current process’s effective group id.

Set the current process’s effective user id.

Set the current process’ group id.

Set the list of supplemental group ids associated with the current process to groups . groups must be a sequence, and each element must be an integer identifying a group. This operation is typically available only to the superuser.

On macOS, the length of groups may not exceed the system-defined maximum number of effective group ids, typically 16. See the documentation for getgroups() for cases where it may not return the same group list set by calling setgroups().

Call the system call setpgrp() or setpgrp(0, 0) depending on which version is implemented (if any). See the Unix manual for the semantics.

Call the system call setpgid() to set the process group id of the process with id pid to the process group with id pgrp . See the Unix manual for the semantics.

Set program scheduling priority. The value which is one of PRIO_PROCESS , PRIO_PGRP , or PRIO_USER , and who is interpreted relative to which (a process identifier for PRIO_PROCESS , process group identifier for PRIO_PGRP , and a user ID for PRIO_USER ). A zero value for who denotes (respectively) the calling process, the process group of the calling process, or the real user ID of the calling process. priority is a value in the range -20 to 19. The default priority is 0; lower priorities cause more favorable scheduling.

Set the current process’s real and effective group ids.

Set the current process’s real, effective, and saved group ids.

Set the current process’s real, effective, and saved user ids.

Set the current process’s real and effective user ids.

Call the system call getsid() . See the Unix manual for the semantics.

Call the system call setsid() . See the Unix manual for the semantics.

Set the current process’s user id.

Return the error message corresponding to the error code in code . On platforms where strerror() returns NULL when given an unknown error number, ValueError is raised.

True if the native OS type of the environment is bytes (eg. False on Windows).

Set the current numeric umask and return the previous umask.

Returns information identifying the current operating system. The return value is an object with five attributes:

sysname - operating system name

nodename - name of machine on network (implementation-defined)

release - operating system release

version - operating system version

machine - hardware identifier

For backwards compatibility, this object is also iterable, behaving like a five-tuple containing sysname , nodename , release , version , and machine in that order.

Some systems truncate nodename to 8 characters or to the leading component; a better way to get the hostname is socket.gethostname() or even socket.gethostbyaddr(socket.gethostname()) .

Availability : recent flavors of Unix.

3.3 sürümünde değişti: Return type changed from a tuple to a tuple-like object with named attributes.

Unset (delete) the environment variable named key . Such changes to the environment affect subprocesses started with os.system() , popen() or fork() and execv() .

Deletion of items in os.environ is automatically translated into a corresponding call to unsetenv() ; however, calls to unsetenv() don’t update os.environ , so it is actually preferable to delete items of os.environ .

Raises an auditing event os.unsetenv with argument key .

3.9 sürümünde değişti: The function is now always available and is also available on Windows.

File Object Creation ¶

These functions create new file objects . (See also open() for opening file descriptors.)

Return an open file object connected to the file descriptor fd . This is an alias of the open() built-in function and accepts the same arguments. The only difference is that the first argument of fdopen() must always be an integer.

File Descriptor Operations ¶

These functions operate on I/O streams referenced using file descriptors.

File descriptors are small integers corresponding to a file that has been opened by the current process. For example, standard input is usually file descriptor 0, standard output is 1, and standard error is 2. Further files opened by a process will then be assigned 3, 4, 5, and so forth. The name “file descriptor” is slightly deceptive; on Unix platforms, sockets and pipes are also referenced by file descriptors.

The fileno() method can be used to obtain the file descriptor associated with a file object when required. Note that using the file descriptor directly will bypass the file object methods, ignoring aspects such as internal buffering of data.

Close file descriptor fd .

This function is intended for low-level I/O and must be applied to a file descriptor as returned by os.open() or pipe() . To close a “file object” returned by the built-in function open() or by popen() or fdopen() , use its close() method.

Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring errors. Equivalent to (but much faster than):

Copy count bytes from file descriptor src , starting from offset offset_src , to file descriptor dst , starting from offset offset_dst . If offset_src is None, then src is read from the current position; respectively for offset_dst . The files pointed by src and dst must reside in the same filesystem, otherwise an OSError is raised with errno set to errno.EXDEV .

This copy is done without the additional cost of transferring data from the kernel to user space and then back into the kernel. Additionally, some filesystems could implement extra optimizations. The copy is done as if both files are opened as binary.

The return value is the amount of bytes copied. This could be less than the amount requested.

Availability : Linux kernel >= 4.5 or glibc >= 2.27.

3.8 sürümüyle geldi.

Return a string describing the encoding of the device associated with fd if it is connected to a terminal; else return None .

Return a duplicate of file descriptor fd . The new file descriptor is non-inheritable .

On Windows, when duplicating a standard stream (0: stdin, 1: stdout, 2: stderr), the new file descriptor is inheritable .

3.4 sürümünde değişti: The new file descriptor is now non-inheritable.

Duplicate file descriptor fd to fd2 , closing the latter first if necessary. Return fd2 . The new file descriptor is inheritable by default or non-inheritable if inheritable is False .

3.4 sürümünde değişti: Add the optional inheritable parameter.

3.7 sürümünde değişti: Return fd2 on success. Previously, None was always returned.

Change the mode of the file given by fd to the numeric mode . See the docs for chmod() for possible values of mode . As of Python 3.3, this is equivalent to os.chmod(fd, mode) .

Raises an auditing event os.chmod with arguments path , mode , dir_fd .

Change the owner and group id of the file given by fd to the numeric uid and gid . To leave one of the ids unchanged, set it to -1. See chown() . As of Python 3.3, this is equivalent to os.chown(fd, uid, gid) .

Raises an auditing event os.chown with arguments path , uid , gid , dir_fd .

Force write of file with filedescriptor fd to disk. Does not force update of metadata.

This function is not available on MacOS.

Return system configuration information relevant to an open file. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given in the pathconf_names dictionary. For configuration variables not included in that mapping, passing an integer for name is also accepted.

If name is a string and is not known, ValueError is raised. If a specific value for name is not supported by the host system, even if it is included in pathconf_names , an OSError is raised with errno.EINVAL for the error number.

As of Python 3.3, this is equivalent to os.pathconf(fd, name) .

Get the status of the file descriptor fd . Return a stat_result object.

As of Python 3.3, this is equivalent to os.stat(fd) .

The stat() function.

Return information about the filesystem containing the file associated with file descriptor fd , like statvfs() . As of Python 3.3, this is equivalent to os.statvfs(fd) .

Force write of file with filedescriptor fd to disk. On Unix, this calls the native fsync() function; on Windows, the MS _commit() function.

If you’re starting with a buffered Python file object f , first do f.flush() , and then do os.fsync(f.fileno()) , to ensure that all internal buffers associated with f are written to disk.

Truncate the file corresponding to file descriptor fd , so that it is at most length bytes in size. As of Python 3.3, this is equivalent to os.truncate(fd, length) .

Raises an auditing event os.truncate with arguments fd , length .

3.5 sürümünde değişti: Added support for Windows

Get the blocking mode of the file descriptor: False if the O_NONBLOCK flag is set, True if the flag is cleared.

See also set_blocking() and socket.socket.setblocking() .

3.5 sürümüyle geldi.

Return True if the file descriptor fd is open and connected to a tty(-like) device, else False .

Apply, test or remove a POSIX lock on an open file descriptor. fd is an open file descriptor. cmd specifies the command to use - one of F_LOCK , F_TLOCK , F_ULOCK or F_TEST . len specifies the section of the file to lock.

Raises an auditing event os.lockf with arguments fd , cmd , len .

Flags that specify what action lockf() will take.

Set the current position of file descriptor fd to position pos , modified by how : SEEK_SET or 0 to set the position relative to the beginning of the file; SEEK_CUR or 1 to set it relative to the current position; SEEK_END or 2 to set it relative to the end of the file. Return the new cursor position in bytes, starting from the beginning.

Parameters to the lseek() function. Their values are 0, 1, and 2, respectively.

3.3 sürümüyle geldi: Some operating systems could support additional values, like os.SEEK_HOLE or os.SEEK_DATA .

Open the file path and set various flags according to flags and possibly its mode according to mode . When computing mode , the current umask value is first masked out. Return the file descriptor for the newly opened file. The new file descriptor is non-inheritable .

For a description of the flag and mode values, see the C run-time documentation; flag constants (like O_RDONLY and O_WRONLY ) are defined in the os module. In particular, on Windows adding O_BINARY is needed to open files in binary mode.

This function can support paths relative to directory descriptors with the dir_fd parameter.

Raises an auditing event open with arguments path , mode , flags .

This function is intended for low-level I/O. For normal usage, use the built-in function open() , which returns a file object with read() and write() methods (and many more). To wrap a file descriptor in a file object, use fdopen() .

3.3 sürümüyle geldi: The dir_fd argument.

3.5 sürümünde değişti: If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

3.6 sürümünde değişti: Accepts a path-like object .

The following constants are options for the flags parameter to the open() function. They can be combined using the bitwise OR operator | . Some of them are not available on all platforms. For descriptions of their availability and use, consult the open(2) manual page on Unix or the MSDN on Windows.

The above constants are available on Unix and Windows.

The above constants are only available on Unix.

3.3 sürümünde değişti: Add O_CLOEXEC constant.

The above constants are only available on Windows.

The above constants are extensions and not present if they are not defined by the C library.

3.4 sürümünde değişti: Add O_PATH on systems that support it. Add O_TMPFILE , only available on Linux Kernel 3.11 or newer.

Open a new pseudo-terminal pair. Return a pair of file descriptors (master, slave) for the pty and the tty, respectively. The new file descriptors are non-inheritable . For a (slightly) more portable approach, use the pty module.

Availability : some flavors of Unix.

3.4 sürümünde değişti: The new file descriptors are now non-inheritable.

Create a pipe. Return a pair of file descriptors (r, w) usable for reading and writing, respectively. The new file descriptor is non-inheritable .

Create a pipe with flags set atomically. flags can be constructed by ORing together one or more of these values: O_NONBLOCK , O_CLOEXEC . Return a pair of file descriptors (r, w) usable for reading and writing, respectively.

Ensures that enough disk space is allocated for the file specified by fd starting from offset and continuing for len bytes.

Announces an intention to access data in a specific pattern thus allowing the kernel to make optimizations. The advice applies to the region of the file specified by fd starting at offset and continuing for len bytes. advice is one of POSIX_FADV_NORMAL , POSIX_FADV_SEQUENTIAL , POSIX_FADV_RANDOM , POSIX_FADV_NOREUSE , POSIX_FADV_WILLNEED or POSIX_FADV_DONTNEED .

Flags that can be used in advice in posix_fadvise() that specify the access pattern that is likely to be used.

Read at most n bytes from file descriptor fd at a position of offset , leaving the file offset unchanged.

Return a bytestring containing the bytes read. If the end of the file referred to by fd has been reached, an empty bytes object is returned.

Read from a file descriptor fd at a position of offset into mutable bytes-like objects buffers , leaving the file offset unchanged. Transfer data into each buffer until it is full and then move on to the next buffer in the sequence to hold the rest of the data.

The flags argument contains a bitwise OR of zero or more of the following flags:

Return the total number of bytes actually read which can be less than the total capacity of all the objects.

The operating system may set a limit ( sysconf() value 'SC_IOV_MAX' ) on the number of buffers that can be used.

Combine the functionality of os.readv() and os.pread() .

Availability : Linux 2.6.30 and newer, FreeBSD 6.0 and newer, OpenBSD 2.7 and newer, AIX 7.1 and newer. Using flags requires Linux 4.6 or newer.

3.7 sürümüyle geldi.

Do not wait for data which is not immediately available. If this flag is specified, the system call will return instantly if it would have to read data from the backing storage or wait for a lock.

If some data was successfully read, it will return the number of bytes read. If no bytes were read, it will return -1 and set errno to errno.EAGAIN .

Availability : Linux 4.14 and newer.

High priority read/write. Allows block-based filesystems to use polling of the device, which provides lower latency, but may use additional resources.

Currently, on Linux, this feature is usable only on a file descriptor opened using the O_DIRECT flag.

Availability : Linux 4.6 and newer.

Write the bytestring in str to file descriptor fd at position of offset , leaving the file offset unchanged.

Return the number of bytes actually written.

Write the buffers contents to file descriptor fd at a offset offset , leaving the file offset unchanged. buffers must be a sequence of bytes-like objects . Buffers are processed in array order. Entire contents of the first buffer is written before proceeding to the second, and so on.

Return the total number of bytes actually written.

Combine the functionality of os.writev() and os.pwrite() .

Availability : Linux 2.6.30 and newer, FreeBSD 6.0 and newer, OpenBSD 2.7 and newer, AIX 7.1 and newer. Using flags requires Linux 4.7 or newer.

Provide a per-write equivalent of the O_DSYNC open(2) flag. This flag effect applies only to the data range written by the system call.

Availability : Linux 4.7 and newer.

Provide a per-write equivalent of the O_SYNC open(2) flag. This flag effect applies only to the data range written by the system call.

Read at most n bytes from file descriptor fd .

This function is intended for low-level I/O and must be applied to a file descriptor as returned by os.open() or pipe() . To read a “file object” returned by the built-in function open() or by popen() or fdopen() , or sys.stdin , use its read() or readline() methods.

Copy count bytes from file descriptor in_fd to file descriptor out_fd starting at offset . Return the number of bytes sent. When EOF is reached return 0 .

The first function notation is supported by all platforms that define sendfile() .

On Linux, if offset is given as None , the bytes are read from the current position of in_fd and the position of in_fd is updated.

The second case may be used on macOS and FreeBSD where headers and trailers are arbitrary sequences of buffers that are written before and after the data from in_fd is written. It returns the same as the first case.

On macOS and FreeBSD, a value of 0 for count specifies to send until the end of in_fd is reached.

All platforms support sockets as out_fd file descriptor, and some platforms allow other types (e.g. regular file, pipe) as well.

Cross-platform applications should not use headers , trailers and flags arguments.

For a higher-level wrapper of sendfile() , see socket.socket.sendfile() .

3.9 sürümünde değişti: Parameters out and in was renamed to out_fd and in_fd .

Set the blocking mode of the specified file descriptor. Set the O_NONBLOCK flag if blocking is False , clear the flag otherwise.

See also get_blocking() and socket.socket.setblocking() .

Parameters to the sendfile() function, if the implementation supports them.

Read from a file descriptor fd into a number of mutable bytes-like objects buffers . Transfer data into each buffer until it is full and then move on to the next buffer in the sequence to hold the rest of the data.

Return the process group associated with the terminal given by fd (an open file descriptor as returned by os.open() ).

Set the process group associated with the terminal given by fd (an open file descriptor as returned by os.open() ) to pg .

Return a string which specifies the terminal device associated with file descriptor fd . If fd is not associated with a terminal device, an exception is raised.

Write the bytestring in str to file descriptor fd .

This function is intended for low-level I/O and must be applied to a file descriptor as returned by os.open() or pipe() . To write a “file object” returned by the built-in function open() or by popen() or fdopen() , or sys.stdout or sys.stderr , use its write() method.

Write the contents of buffers to file descriptor fd . buffers must be a sequence of bytes-like objects . Buffers are processed in array order. Entire contents of the first buffer is written before proceeding to the second, and so on.

Returns the total number of bytes actually written.

Querying the size of a terminal ¶

Return the size of the terminal window as (columns, lines) , tuple of type terminal_size .

The optional argument fd (default STDOUT_FILENO , or standard output) specifies which file descriptor should be queried.

If the file descriptor is not connected to a terminal, an OSError is raised.

shutil.get_terminal_size() is the high-level function which should normally be used, os.get_terminal_size is the low-level implementation.

A subclass of tuple, holding (columns, lines) of the terminal window size.

Width of the terminal window in characters.

Height of the terminal window in characters.

Inheritance of File Descriptors ¶

3.4 sürümüyle geldi.

A file descriptor has an “inheritable” flag which indicates if the file descriptor can be inherited by child processes. Since Python 3.4, file descriptors created by Python are non-inheritable by default.

On UNIX, non-inheritable file descriptors are closed in child processes at the execution of a new program, other file descriptors are inherited.

On Windows, non-inheritable handles and file descriptors are closed in child processes, except for standard streams (file descriptors 0, 1 and 2: stdin, stdout and stderr), which are always inherited. Using spawn* functions, all inheritable handles and all inheritable file descriptors are inherited. Using the subprocess module, all file descriptors except standard streams are closed, and inheritable handles are only inherited if the close_fds parameter is False .

Get the “inheritable” flag of the specified file descriptor (a boolean).

Set the “inheritable” flag of the specified file descriptor.

Get the “inheritable” flag of the specified handle (a boolean).

Availability : Windows.

Set the “inheritable” flag of the specified handle.

Files and Directories ¶

On some Unix platforms, many of these functions support one or more of these features:

specifying a file descriptor: Normally the path argument provided to functions in the os module must be a string specifying a file path. However, some functions now alternatively accept an open file descriptor for their path argument. The function will then operate on the file referred to by the descriptor. (For POSIX systems, Python will call the variant of the function prefixed with f (e.g. call fchdir instead of chdir ).)

You can check whether or not path can be specified as a file descriptor for a particular function on your platform using os.supports_fd . If this functionality is unavailable, using it will raise a NotImplementedError .

If the function also supports dir_fd or follow_symlinks arguments, it’s an error to specify one of those when supplying path as a file descriptor.

paths relative to directory descriptors: If dir_fd is not None , it should be a file descriptor referring to a directory, and the path to operate on should be relative; path will then be relative to that directory. If the path is absolute, dir_fd is ignored. (For POSIX systems, Python will call the variant of the function with an at suffix and possibly prefixed with f (e.g. call faccessat instead of access ).

You can check whether or not dir_fd is supported for a particular function on your platform using os.supports_dir_fd . If it’s unavailable, using it will raise a NotImplementedError .

not following symlinks: If follow_symlinks is False , and the last element of the path to operate on is a symbolic link, the function will operate on the symbolic link itself rather than the file pointed to by the link. (For POSIX systems, Python will call the l... variant of the function.)

You can check whether or not follow_symlinks is supported for a particular function on your platform using os.supports_follow_symlinks . If it’s unavailable, using it will raise a NotImplementedError .

Use the real uid/gid to test for access to path . Note that most operations will use the effective uid/gid, therefore this routine can be used in a suid/sgid environment to test if the invoking user has the specified access to path . mode should be F_OK to test the existence of path , or it can be the inclusive OR of one or more of R_OK , W_OK , and X_OK to test permissions. Return True if access is allowed, False if not. See the Unix man page access(2) for more information.

This function can support specifying paths relative to directory descriptors and not following symlinks .

If effective_ids is True , access() will perform its access checks using the effective uid/gid instead of the real uid/gid. effective_ids may not be supported on your platform; you can check whether or not it is available using os.supports_effective_ids . If it is unavailable, using it will raise a NotImplementedError .

Using access() to check if a user is authorized to e.g. open a file before actually doing so using open() creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it. It’s preferable to use EAFP techniques. For example:

is better written as:

I/O operations may fail even when access() indicates that they would succeed, particularly for operations on network filesystems which may have permissions semantics beyond the usual POSIX permission-bit model.

3.3 sürümünde değişti: Added the dir_fd , effective_ids , and follow_symlinks parameters.

Values to pass as the mode parameter of access() to test the existence, readability, writability and executability of path , respectively.

Change the current working directory to path .

This function can support specifying a file descriptor . The descriptor must refer to an opened directory, not an open file.

This function can raise OSError and subclasses such as FileNotFoundError , PermissionError , and NotADirectoryError .

Raises an auditing event os.chdir with argument path .

3.3 sürümüyle geldi: Added support for specifying path as a file descriptor on some platforms.

Set the flags of path to the numeric flags . flags may take a combination (bitwise OR) of the following values (as defined in the stat module):

stat.UF_NODUMP

stat.UF_IMMUTABLE

stat.UF_APPEND

stat.UF_OPAQUE

stat.UF_NOUNLINK

stat.UF_COMPRESSED

stat.UF_HIDDEN

stat.SF_ARCHIVED

stat.SF_IMMUTABLE

stat.SF_APPEND

stat.SF_NOUNLINK

stat.SF_SNAPSHOT

This function can support not following symlinks .

Raises an auditing event os.chflags with arguments path , flags .

3.3 sürümüyle geldi: The follow_symlinks argument.

Change the mode of path to the numeric mode . mode may take one of the following values (as defined in the stat module) or bitwise ORed combinations of them:

stat.S_ISUID

stat.S_ISGID

stat.S_ENFMT

stat.S_ISVTX

stat.S_IREAD

stat.S_IWRITE

stat.S_IEXEC

stat.S_IRWXU

stat.S_IRUSR

stat.S_IWUSR

stat.S_IXUSR

stat.S_IRWXG

stat.S_IRGRP

stat.S_IWGRP

stat.S_IXGRP

stat.S_IRWXO

stat.S_IROTH

stat.S_IWOTH

stat.S_IXOTH

This function can support specifying a file descriptor , paths relative to directory descriptors and not following symlinks .

Although Windows supports chmod() , you can only set the file’s read-only flag with it (via the stat.S_IWRITE and stat.S_IREAD constants or a corresponding integer value). All other bits are ignored.

3.3 sürümüyle geldi: Added support for specifying path as an open file descriptor, and the dir_fd and follow_symlinks arguments.

Change the owner and group id of path to the numeric uid and gid . To leave one of the ids unchanged, set it to -1.

See shutil.chown() for a higher-level function that accepts names in addition to numeric ids.

3.6 sürümünde değişti: Supports a path-like object .

Change the root directory of the current process to path .

Change the current working directory to the directory represented by the file descriptor fd . The descriptor must refer to an opened directory, not an open file. As of Python 3.3, this is equivalent to os.chdir(fd) .

Return a string representing the current working directory.

Return a bytestring representing the current working directory.

3.8 sürümünde değişti: The function now uses the UTF-8 encoding on Windows, rather than the ANSI code page: see PEP 529 for the rationale. The function is no longer deprecated on Windows.

Set the flags of path to the numeric flags , like chflags() , but do not follow symbolic links. As of Python 3.3, this is equivalent to os.chflags(path, flags, follow_symlinks=False) .

Change the mode of path to the numeric mode . If path is a symlink, this affects the symlink rather than the target. See the docs for chmod() for possible values of mode . As of Python 3.3, this is equivalent to os.chmod(path, mode, follow_symlinks=False) .

Change the owner and group id of path to the numeric uid and gid . This function will not follow symbolic links. As of Python 3.3, this is equivalent to os.chown(path, uid, gid, follow_symlinks=False) .

Create a hard link pointing to src named dst .

This function can support specifying src_dir_fd and/or dst_dir_fd to supply paths relative to directory descriptors , and not following symlinks .

Raises an auditing event os.link with arguments src , dst , src_dir_fd , dst_dir_fd .

3.2 sürümünde değişti: Added Windows support.

3.3 sürümüyle geldi: Added the src_dir_fd , dst_dir_fd , and follow_symlinks arguments.

3.6 sürümünde değişti: Accepts a path-like object for src and dst .

Return a list containing the names of the entries in the directory given by path . The list is in arbitrary order, and does not include the special entries '.' and '..' even if they are present in the directory. If a file is removed from or added to the directory during the call of this function, whether a name for that file be included is unspecified.

path may be a path-like object . If path is of type bytes (directly or indirectly through the PathLike interface), the filenames returned will also be of type bytes ; in all other circumstances, they will be of type str .

This function can also support specifying a file descriptor ; the file descriptor must refer to a directory.

Raises an auditing event os.listdir with argument path .

To encode str filenames to bytes , use fsencode() .

The scandir() function returns directory entries along with file attribute information, giving better performance for many common use cases.

3.2 sürümünde değişti: The path parameter became optional.

3.3 sürümüyle geldi: Added support for specifying path as an open file descriptor.

Perform the equivalent of an lstat() system call on the given path. Similar to stat() , but does not follow symbolic links. Return a stat_result object.

On platforms that do not support symbolic links, this is an alias for stat() .

As of Python 3.3, this is equivalent to os.stat(path, dir_fd=dir_fd, follow_symlinks=False) .

This function can also support paths relative to directory descriptors .

3.2 sürümünde değişti: Added support for Windows 6.0 (Vista) symbolic links.

3.3 sürümünde değişti: Added the dir_fd parameter.

3.8 sürümünde değişti: On Windows, now opens reparse points that represent another path (name surrogates), including symbolic links and directory junctions. Other kinds of reparse points are resolved by the operating system as for stat() .

Create a directory named path with numeric mode mode .

If the directory already exists, FileExistsError is raised. If a parent directory in the path does not exist, FileNotFoundError is raised.

On some systems, mode is ignored. Where it is used, the current umask value is first masked out. If bits other than the last 9 (i.e. the last 3 digits of the octal representation of the mode ) are set, their meaning is platform-dependent. On some platforms, they are ignored and you should call chmod() explicitly to set them.

On Windows, a mode of 0o700 is specifically handled to apply access control to the new directory such that only the current user and administrators have access. Other values of mode are ignored.

It is also possible to create temporary directories; see the tempfile module’s tempfile.mkdtemp() function.

Raises an auditing event os.mkdir with arguments path , mode , dir_fd .

3.9.20 sürümünde değişti: Windows now handles a mode of 0o700 .

Recursive directory creation function. Like mkdir() , but makes all intermediate-level directories needed to contain the leaf directory.

The mode parameter is passed to mkdir() for creating the leaf directory; see the mkdir() description for how it is interpreted. To set the file permission bits of any newly-created parent directories you can set the umask before invoking makedirs() . The file permission bits of existing parent directories are not changed.

If exist_ok is False (the default), an FileExistsError is raised if the target directory already exists.

makedirs() will become confused if the path elements to create include pardir (eg. “..” on UNIX systems).

This function handles UNC paths correctly.

3.2 sürümüyle geldi: The exist_ok parameter.

3.4.1 sürümünde değişti: Before Python 3.4.1, if exist_ok was True and the directory existed, makedirs() would still raise an error if mode did not match the mode of the existing directory. Since this behavior was impossible to implement safely, it was removed in Python 3.4.1. See bpo-21082 .

3.7 sürümünde değişti: The mode argument no longer affects the file permission bits of newly-created intermediate-level directories.

Create a FIFO (a named pipe) named path with numeric mode mode . The current umask value is first masked out from the mode.

FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted (for example with os.unlink() ). Generally, FIFOs are used as rendezvous between “client” and “server” type processes: the server opens the FIFO for reading, and the client opens it for writing. Note that mkfifo() doesn’t open the FIFO — it just creates the rendezvous point.

Create a filesystem node (file, device special file or named pipe) named path . mode specifies both the permissions to use and the type of node to be created, being combined (bitwise OR) with one of stat.S_IFREG , stat.S_IFCHR , stat.S_IFBLK , and stat.S_IFIFO (those constants are available in stat ). For stat.S_IFCHR and stat.S_IFBLK , device defines the newly created device special file (probably using os.makedev() ), otherwise it is ignored.

Extract the device major number from a raw device number (usually the st_dev or st_rdev field from stat ).

Extract the device minor number from a raw device number (usually the st_dev or st_rdev field from stat ).

Compose a raw device number from the major and minor device numbers.

Return system configuration information relevant to a named file. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given in the pathconf_names dictionary. For configuration variables not included in that mapping, passing an integer for name is also accepted.

This function can support specifying a file descriptor .

Dictionary mapping names accepted by pathconf() and fpathconf() to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system.

Return a string representing the path to which the symbolic link points. The result may be either an absolute or relative pathname; if it is relative, it may be converted to an absolute pathname using os.path.join(os.path.dirname(path), result) .

If the path is a string object (directly or indirectly through a PathLike interface), the result will also be a string object, and the call may raise a UnicodeDecodeError. If the path is a bytes object (direct or indirectly), the result will be a bytes object.

When trying to resolve a path that may contain links, use realpath() to properly handle recursion and platform differences.

3.6 sürümünde değişti: Accepts a path-like object on Unix.

3.8 sürümünde değişti: Accepts a path-like object and a bytes object on Windows.

3.8 sürümünde değişti: Added support for directory junctions, and changed to return the substitution path (which typically includes \\?\ prefix) rather than the optional “print name” field that was previously returned.

Remove (delete) the file path . If path is a directory, an IsADirectoryError is raised. Use rmdir() to remove directories. If the file does not exist, a FileNotFoundError is raised.

This function can support paths relative to directory descriptors .

On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use.

This function is semantically identical to unlink() .

Raises an auditing event os.remove with arguments path , dir_fd .

Remove directories recursively. Works like rmdir() except that, if the leaf directory is successfully removed, removedirs() tries to successively remove every parent directory mentioned in path until an error is raised (which is ignored, because it generally means that a parent directory is not empty). For example, os.removedirs('foo/bar/baz') will first remove the directory 'foo/bar/baz' , and then remove 'foo/bar' and 'foo' if they are empty. Raises OSError if the leaf directory could not be successfully removed.

Rename the file or directory src to dst . If dst exists, the operation will fail with an OSError subclass in a number of cases:

On Windows, if dst exists a FileExistsError is always raised.

On Unix, if src is a file and dst is a directory or vice-versa, an IsADirectoryError or a NotADirectoryError will be raised respectively. If both are directories and dst is empty, dst will be silently replaced. If dst is a non-empty directory, an OSError is raised. If both are files, dst it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement).

This function can support specifying src_dir_fd and/or dst_dir_fd to supply paths relative to directory descriptors .

If you want cross-platform overwriting of the destination, use replace() .

Raises an auditing event os.rename with arguments src , dst , src_dir_fd , dst_dir_fd .

3.3 sürümüyle geldi: The src_dir_fd and dst_dir_fd arguments.

Recursive directory or file renaming function. Works like rename() , except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned away using removedirs() .

This function can fail with the new directory structure made if you lack permissions needed to remove the leaf directory or file.

3.6 sürümünde değişti: Accepts a path-like object for old and new .

Rename the file or directory src to dst . If dst is a non-empty directory, OSError will be raised. If dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement).

Remove (delete) the directory path . If the directory does not exist or is not empty, an FileNotFoundError or an OSError is raised respectively. In order to remove whole directory trees, shutil.rmtree() can be used.

Raises an auditing event os.rmdir with arguments path , dir_fd .

3.3 sürümüyle geldi: The dir_fd parameter.

Return an iterator of os.DirEntry objects corresponding to the entries in the directory given by path . The entries are yielded in arbitrary order, and the special entries '.' and '..' are not included. If a file is removed from or added to the directory after creating the iterator, whether an entry for that file be included is unspecified.

Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because os.DirEntry objects expose this information if the operating system provides it when scanning a directory. All os.DirEntry methods may perform a system call, but is_dir() and is_file() usually only require a system call for symbolic links; os.DirEntry.stat() always requires a system call on Unix but only requires one for symbolic links on Windows.

path may be a path-like object . If path is of type bytes (directly or indirectly through the PathLike interface), the type of the name and path attributes of each os.DirEntry will be bytes ; in all other circumstances, they will be of type str .

Raises an auditing event os.scandir with argument path .

The scandir() iterator supports the context manager protocol and has the following method:

Close the iterator and free acquired resources.

This is called automatically when the iterator is exhausted or garbage collected, or when an error happens during iterating. However it is advisable to call it explicitly or use the with statement.

The following example shows a simple use of scandir() to display all the files (excluding directories) in the given path that don’t start with '.' . The entry.is_file() call will generally not make an additional system call:

On Unix-based systems, scandir() uses the system’s opendir() and readdir() functions. On Windows, it uses the Win32 FindFirstFileW and FindNextFileW functions.

3.6 sürümüyle geldi: Added support for the context manager protocol and the close() method. If a scandir() iterator is neither exhausted nor explicitly closed a ResourceWarning will be emitted in its destructor.

The function accepts a path-like object .

3.7 sürümünde değişti: Added support for file descriptors on Unix.

Object yielded by scandir() to expose the file path and other file attributes of a directory entry.

scandir() will provide as much of this information as possible without making additional system calls. When a stat() or lstat() system call is made, the os.DirEntry object will cache the result.

os.DirEntry instances are not intended to be stored in long-lived data structures; if you know the file metadata has changed or if a long time has elapsed since calling scandir() , call os.stat(entry.path) to fetch up-to-date information.

Because the os.DirEntry methods can make operating system calls, they may also raise OSError . If you need very fine-grained control over errors, you can catch OSError when calling one of the os.DirEntry methods and handle as appropriate.

To be directly usable as a path-like object , os.DirEntry implements the PathLike interface.

Attributes and methods on a os.DirEntry instance are as follows:

The entry’s base filename, relative to the scandir() path argument.

The name attribute will be bytes if the scandir() path argument is of type bytes and str otherwise. Use fsdecode() to decode byte filenames.

The entry’s full path name: equivalent to os.path.join(scandir_path, entry.name) where scandir_path is the scandir() path argument. The path is only absolute if the scandir() path argument was absolute. If the scandir() path argument was a file descriptor , the path attribute is the same as the name attribute.

The path attribute will be bytes if the scandir() path argument is of type bytes and str otherwise. Use fsdecode() to decode byte filenames.

Return the inode number of the entry.

The result is cached on the os.DirEntry object. Use os.stat(entry.path, follow_symlinks=False).st_ino to fetch up-to-date information.

On the first, uncached call, a system call is required on Windows but not on Unix.

Return True if this entry is a directory or a symbolic link pointing to a directory; return False if the entry is or points to any other kind of file, or if it doesn’t exist anymore.

If follow_symlinks is False , return True only if this entry is a directory (without following symlinks); return False if the entry is any other kind of file or if it doesn’t exist anymore.

The result is cached on the os.DirEntry object, with a separate cache for follow_symlinks True and False . Call os.stat() along with stat.S_ISDIR() to fetch up-to-date information.

On the first, uncached call, no system call is required in most cases. Specifically, for non-symlinks, neither Windows or Unix require a system call, except on certain Unix file systems, such as network file systems, that return dirent.d_type == DT_UNKNOWN . If the entry is a symlink, a system call will be required to follow the symlink unless follow_symlinks is False .

This method can raise OSError , such as PermissionError , but FileNotFoundError is caught and not raised.

Return True if this entry is a file or a symbolic link pointing to a file; return False if the entry is or points to a directory or other non-file entry, or if it doesn’t exist anymore.

If follow_symlinks is False , return True only if this entry is a file (without following symlinks); return False if the entry is a directory or other non-file entry, or if it doesn’t exist anymore.

The result is cached on the os.DirEntry object. Caching, system calls made, and exceptions raised are as per is_dir() .

Return True if this entry is a symbolic link (even if broken); return False if the entry points to a directory or any kind of file, or if it doesn’t exist anymore.

The result is cached on the os.DirEntry object. Call os.path.islink() to fetch up-to-date information.

On the first, uncached call, no system call is required in most cases. Specifically, neither Windows or Unix require a system call, except on certain Unix file systems, such as network file systems, that return dirent.d_type == DT_UNKNOWN .

Return a stat_result object for this entry. This method follows symbolic links by default; to stat a symbolic link add the follow_symlinks=False argument.

On Unix, this method always requires a system call. On Windows, it only requires a system call if follow_symlinks is True and the entry is a reparse point (for example, a symbolic link or directory junction).

On Windows, the st_ino , st_dev and st_nlink attributes of the stat_result are always set to zero. Call os.stat() to get these attributes.

The result is cached on the os.DirEntry object, with a separate cache for follow_symlinks True and False . Call os.stat() to fetch up-to-date information.

Note that there is a nice correspondence between several attributes and methods of os.DirEntry and of pathlib.Path . In particular, the name attribute has the same meaning, as do the is_dir() , is_file() , is_symlink() and stat() methods.

3.6 sürümünde değişti: Added support for the PathLike interface. Added support for bytes paths on Windows.

Get the status of a file or a file descriptor. Perform the equivalent of a stat() system call on the given path. path may be specified as either a string or bytes – directly or indirectly through the PathLike interface – or as an open file descriptor. Return a stat_result object.

This function normally follows symlinks; to stat a symlink add the argument follow_symlinks=False , or use lstat() .

This function can support specifying a file descriptor and not following symlinks .

On Windows, passing follow_symlinks=False will disable following all name-surrogate reparse points, which includes symlinks and directory junctions. Other types of reparse points that do not resemble links or that the operating system is unable to follow will be opened directly. When following a chain of multiple links, this may result in the original link being returned instead of the non-link that prevented full traversal. To obtain stat results for the final path in this case, use the os.path.realpath() function to resolve the path name as far as possible and call lstat() on the result. This does not apply to dangling symlinks or junction points, which will raise the usual exceptions.

fstat() and lstat() functions.

3.3 sürümüyle geldi: Added the dir_fd and follow_symlinks arguments, specifying a file descriptor instead of a path.

3.8 sürümünde değişti: On Windows, all reparse points that can be resolved by the operating system are now followed, and passing follow_symlinks=False disables following all name surrogate reparse points. If the operating system reaches a reparse point that it is not able to follow, stat now returns the information for the original path as if follow_symlinks=False had been specified instead of raising an error.

Object whose attributes correspond roughly to the members of the stat structure. It is used for the result of os.stat() , os.fstat() and os.lstat() .

Attributes:

File mode: file type and file mode bits (permissions).

Platform dependent, but if non-zero, uniquely identifies the file for a given value of st_dev . Typically:

the inode number on Unix,

the file index on Windows

Identifier of the device on which this file resides.

Number of hard links.

User identifier of the file owner.

Group identifier of the file owner.

Size of the file in bytes, if it is a regular file or a symbolic link. The size of a symbolic link is the length of the pathname it contains, without a terminating null byte.

Timestamps:

Time of most recent access expressed in seconds.

Time of most recent content modification expressed in seconds.

Platform dependent:

the time of most recent metadata change on Unix,

the time of creation on Windows, expressed in seconds.

Time of most recent access expressed in nanoseconds as an integer.

Time of most recent content modification expressed in nanoseconds as an integer.

the time of creation on Windows, expressed in nanoseconds as an integer.

The exact meaning and resolution of the st_atime , st_mtime , and st_ctime attributes depend on the operating system and the file system. For example, on Windows systems using the FAT or FAT32 file systems, st_mtime has 2-second resolution, and st_atime has only 1-day resolution. See your operating system documentation for details.

Similarly, although st_atime_ns , st_mtime_ns , and st_ctime_ns are always expressed in nanoseconds, many systems do not provide nanosecond precision. On systems that do provide nanosecond precision, the floating-point object used to store st_atime , st_mtime , and st_ctime cannot preserve all of it, and as such will be slightly inexact. If you need the exact timestamps you should always use st_atime_ns , st_mtime_ns , and st_ctime_ns .

On some Unix systems (such as Linux), the following attributes may also be available:

Number of 512-byte blocks allocated for file. This may be smaller than st_size /512 when the file has holes.

“Preferred” blocksize for efficient file system I/O. Writing to a file in smaller chunks may cause an inefficient read-modify-rewrite.

Type of device if an inode device.

User defined flags for file.

On other Unix systems (such as FreeBSD), the following attributes may be available (but may be only filled out if root tries to use them):

File generation number.

Time of file creation.

On Solaris and derivatives, the following attributes may also be available:

String that uniquely identifies the type of the filesystem that contains the file.

On macOS systems, the following attributes may also be available:

Real size of the file.

Creator of the file.

On Windows systems, the following attributes are also available:

Windows file attributes: dwFileAttributes member of the BY_HANDLE_FILE_INFORMATION structure returned by GetFileInformationByHandle() . See the FILE_ATTRIBUTE_* constants in the stat module.

When st_file_attributes has the FILE_ATTRIBUTE_REPARSE_POINT set, this field contains the tag identifying the type of reparse point. See the IO_REPARSE_TAG_* constants in the stat module.

The standard module stat defines functions and constants that are useful for extracting information from a stat structure. (On Windows, some items are filled with dummy values.)

For backward compatibility, a stat_result instance is also accessible as a tuple of at least 10 integers giving the most important (and portable) members of the stat structure, in the order st_mode , st_ino , st_dev , st_nlink , st_uid , st_gid , st_size , st_atime , st_mtime , st_ctime . More items may be added at the end by some implementations. For compatibility with older Python versions, accessing stat_result as a tuple always returns integers.

3.3 sürümüyle geldi: Added the st_atime_ns , st_mtime_ns , and st_ctime_ns members.

3.5 sürümüyle geldi: Added the st_file_attributes member on Windows.

3.5 sürümünde değişti: Windows now returns the file index as st_ino when available.

3.7 sürümüyle geldi: Added the st_fstype member to Solaris/derivatives.

3.8 sürümüyle geldi: Added the st_reparse_tag member on Windows.

3.8 sürümünde değişti: On Windows, the st_mode member now identifies special files as S_IFCHR , S_IFIFO or S_IFBLK as appropriate.

Perform a statvfs() system call on the given path. The return value is an object whose attributes describe the filesystem on the given path, and correspond to the members of the statvfs structure, namely: f_bsize , f_frsize , f_blocks , f_bfree , f_bavail , f_files , f_ffree , f_favail , f_flag , f_namemax , f_fsid .

Two module-level constants are defined for the f_flag attribute’s bit-flags: if ST_RDONLY is set, the filesystem is mounted read-only, and if ST_NOSUID is set, the semantics of setuid/setgid bits are disabled or not supported.

Additional module-level constants are defined for GNU/glibc based systems. These are ST_NODEV (disallow access to device special files), ST_NOEXEC (disallow program execution), ST_SYNCHRONOUS (writes are synced at once), ST_MANDLOCK (allow mandatory locks on an FS), ST_WRITE (write on file/directory/symlink), ST_APPEND (append-only file), ST_IMMUTABLE (immutable file), ST_NOATIME (do not update access times), ST_NODIRATIME (do not update directory access times), ST_RELATIME (update atime relative to mtime/ctime).

3.2 sürümünde değişti: The ST_RDONLY and ST_NOSUID constants were added.

3.4 sürümünde değişti: The ST_NODEV , ST_NOEXEC , ST_SYNCHRONOUS , ST_MANDLOCK , ST_WRITE , ST_APPEND , ST_IMMUTABLE , ST_NOATIME , ST_NODIRATIME , and ST_RELATIME constants were added.

3.7 sürümüyle geldi: Added f_fsid .

A set object indicating which functions in the os module accept an open file descriptor for their dir_fd parameter. Different platforms provide different features, and the underlying functionality Python uses to implement the dir_fd parameter is not available on all platforms Python supports. For consistency’s sake, functions that may support dir_fd always allow specifying the parameter, but will throw an exception if the functionality is used when it’s not locally available. (Specifying None for dir_fd is always supported on all platforms.)

To check whether a particular function accepts an open file descriptor for its dir_fd parameter, use the in operator on supports_dir_fd . As an example, this expression evaluates to True if os.stat() accepts open file descriptors for dir_fd on the local platform:

Currently dir_fd parameters only work on Unix platforms; none of them work on Windows.

A set object indicating whether os.access() permits specifying True for its effective_ids parameter on the local platform. (Specifying False for effective_ids is always supported on all platforms.) If the local platform supports it, the collection will contain os.access() ; otherwise it will be empty.

This expression evaluates to True if os.access() supports effective_ids=True on the local platform:

Currently effective_ids is only supported on Unix platforms; it does not work on Windows.

A set object indicating which functions in the os module permit specifying their path parameter as an open file descriptor on the local platform. Different platforms provide different features, and the underlying functionality Python uses to accept open file descriptors as path arguments is not available on all platforms Python supports.

To determine whether a particular function permits specifying an open file descriptor for its path parameter, use the in operator on supports_fd . As an example, this expression evaluates to True if os.chdir() accepts open file descriptors for path on your local platform:

A set object indicating which functions in the os module accept False for their follow_symlinks parameter on the local platform. Different platforms provide different features, and the underlying functionality Python uses to implement follow_symlinks is not available on all platforms Python supports. For consistency’s sake, functions that may support follow_symlinks always allow specifying the parameter, but will throw an exception if the functionality is used when it’s not locally available. (Specifying True for follow_symlinks is always supported on all platforms.)

To check whether a particular function accepts False for its follow_symlinks parameter, use the in operator on supports_follow_symlinks . As an example, this expression evaluates to True if you may specify follow_symlinks=False when calling os.stat() on the local platform:

Create a symbolic link pointing to src named dst .

On Windows, a symlink represents either a file or a directory, and does not morph to the target dynamically. If the target is present, the type of the symlink will be created to match. Otherwise, the symlink will be created as a directory if target_is_directory is True or a file symlink (the default) otherwise. On non-Windows platforms, target_is_directory is ignored.

On newer versions of Windows 10, unprivileged accounts can create symlinks if Developer Mode is enabled. When Developer Mode is not available/enabled, the SeCreateSymbolicLinkPrivilege privilege is required, or the process must be run as an administrator.

OSError is raised when the function is called by an unprivileged user.

Raises an auditing event os.symlink with arguments src , dst , dir_fd .

3.3 sürümüyle geldi: Added the dir_fd argument, and now allow target_is_directory on non-Windows platforms.

3.8 sürümünde değişti: Added support for unelevated symlinks on Windows with Developer Mode.

Force write of everything to disk.

Truncate the file corresponding to path , so that it is at most length bytes in size.

Raises an auditing event os.truncate with arguments path , length .

Remove (delete) the file path . This function is semantically identical to remove() ; the unlink name is its traditional Unix name. Please see the documentation for remove() for further information.

Set the access and modified times of the file specified by path .

utime() takes two optional parameters, times and ns . These specify the times set on path and are used as follows:

If ns is specified, it must be a 2-tuple of the form (atime_ns, mtime_ns) where each member is an int expressing nanoseconds.

If times is not None , it must be a 2-tuple of the form (atime, mtime) where each member is an int or float expressing seconds.

If times is None and ns is unspecified, this is equivalent to specifying ns=(atime_ns, mtime_ns) where both times are the current time.

It is an error to specify tuples for both times and ns .

Note that the exact times you set here may not be returned by a subsequent stat() call, depending on the resolution with which your operating system records access and modification times; see stat() . The best way to preserve exact times is to use the st_atime_ns and st_mtime_ns fields from the os.stat() result object with the ns parameter to utime .

Raises an auditing event os.utime with arguments path , times , ns , dir_fd .

3.3 sürümüyle geldi: Added support for specifying path as an open file descriptor, and the dir_fd , follow_symlinks , and ns parameters.

Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames) .

dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..' ). filenames is a list of the names of the non-directory files in dirpath . Note that the names in the lists contain no path components. To get a full path (which begins with top ) to a file or directory in dirpath , do os.path.join(dirpath, name) . Whether or not the lists are sorted depends on the file system. If a file is removed from or added to the dirpath directory during generating the lists, whether a name for that file be included is unspecified.

If optional argument topdown is True or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). If topdown is False , the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom-up). No matter the value of topdown , the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated.

When topdown is True , the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames ; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again. Modifying dirnames when topdown is False has no effect on the behavior of the walk, because in bottom-up mode the directories in dirnames are generated before dirpath itself is generated.

By default, errors from the scandir() call are ignored. If optional argument onerror is specified, it should be a function; it will be called with one argument, an OSError instance. It can report the error to continue with the walk, or raise the exception to abort the walk. Note that the filename is available as the filename attribute of the exception object.

By default, walk() will not walk down into symbolic links that resolve to directories. Set followlinks to True to visit directories pointed to by symlinks, on systems that support them.

Be aware that setting followlinks to True can lead to infinite recursion if a link points to a parent directory of itself. walk() does not keep track of the directories it visited already.

If you pass a relative pathname, don’t change the current working directory between resumptions of walk() . walk() never changes the current directory, and assumes that its caller doesn’t either.

This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn’t look under any CVS subdirectory:

In the next example (simple implementation of shutil.rmtree() ), walking the tree bottom-up is essential, rmdir() doesn’t allow deleting a directory before the directory is empty:

Raises an auditing event os.walk with arguments top , topdown , onerror , followlinks .

3.5 sürümünde değişti: This function now calls os.scandir() instead of os.listdir() , making it faster by reducing the number of calls to os.stat() .

This behaves exactly like walk() , except that it yields a 4-tuple (dirpath, dirnames, filenames, dirfd) , and it supports dir_fd .

dirpath , dirnames and filenames are identical to walk() output, and dirfd is a file descriptor referring to the directory dirpath .

This function always supports paths relative to directory descriptors and not following symlinks . Note however that, unlike other functions, the fwalk() default value for follow_symlinks is False .

Since fwalk() yields file descriptors, those are only valid until the next iteration step, so you should duplicate them (e.g. with dup() ) if you want to keep them longer.

In the next example, walking the tree bottom-up is essential: rmdir() doesn’t allow deleting a directory before the directory is empty:

Raises an auditing event os.fwalk with arguments top , topdown , onerror , follow_symlinks , dir_fd .

3.7 sürümünde değişti: Added support for bytes paths.

Create an anonymous file and return a file descriptor that refers to it. flags must be one of the os.MFD_* constants available on the system (or a bitwise ORed combination of them). By default, the new file descriptor is non-inheritable .

The name supplied in name is used as a filename and will be displayed as the target of the corresponding symbolic link in the directory /proc/self/fd/ . The displayed name is always prefixed with memfd: and serves only for debugging purposes. Names do not affect the behavior of the file descriptor, and as such multiple files can have the same name without any side effects.

Availability : Linux 3.17 or newer with glibc 2.27 or newer.

These flags can be passed to memfd_create() .

Availability : Linux 3.17 or newer with glibc 2.27 or newer. The MFD_HUGE* flags are only available since Linux 4.14.

Linux extended attributes ¶

These functions are all available on Linux only.

Return the value of the extended filesystem attribute attribute for path . attribute can be bytes or str (directly or indirectly through the PathLike interface). If it is str, it is encoded with the filesystem encoding.

Raises an auditing event os.getxattr with arguments path , attribute .

3.6 sürümünde değişti: Accepts a path-like object for path and attribute .

Return a list of the extended filesystem attributes on path . The attributes in the list are represented as strings decoded with the filesystem encoding. If path is None , listxattr() will examine the current directory.

Raises an auditing event os.listxattr with argument path .

Removes the extended filesystem attribute attribute from path . attribute should be bytes or str (directly or indirectly through the PathLike interface). If it is a string, it is encoded with the filesystem encoding.

Raises an auditing event os.removexattr with arguments path , attribute .

Set the extended filesystem attribute attribute on path to value . attribute must be a bytes or str with no embedded NULs (directly or indirectly through the PathLike interface). If it is a str, it is encoded with the filesystem encoding. flags may be XATTR_REPLACE or XATTR_CREATE . If XATTR_REPLACE is given and the attribute does not exist, ENODATA will be raised. If XATTR_CREATE is given and the attribute already exists, the attribute will not be created and EEXISTS will be raised.

A bug in Linux kernel versions less than 2.6.39 caused the flags argument to be ignored on some filesystems.

Raises an auditing event os.setxattr with arguments path , attribute , value , flags .

The maximum size the value of an extended attribute can be. Currently, this is 64 KiB on Linux.

This is a possible value for the flags argument in setxattr() . It indicates the operation must create an attribute.

This is a possible value for the flags argument in setxattr() . It indicates the operation must replace an existing attribute.

Process Management ¶

These functions may be used to create and manage processes.

The various exec* functions take a list of arguments for the new program loaded into the process. In each case, the first of these arguments is passed to the new program as its own name rather than as an argument a user may have typed on a command line. For the C programmer, this is the argv[0] passed to a program’s main() . For example, os.execv('/bin/echo', ['foo', 'bar']) will only print bar on standard output; foo will seem to be ignored.

Generate a SIGABRT signal to the current process. On Unix, the default behavior is to produce a core dump; on Windows, the process immediately returns an exit code of 3 . Be aware that calling this function will not call the Python signal handler registered for SIGABRT with signal.signal() .

Add a path to the DLL search path.

This search path is used when resolving dependencies for imported extension modules (the module itself is resolved through sys.path ), and also by ctypes .

Remove the directory by calling close() on the returned object or using it in a with statement.

See the Microsoft documentation for more information about how DLLs are loaded.

Raises an auditing event os.add_dll_directory with argument path .

3.8 sürümüyle geldi: Previous versions of CPython would resolve DLLs using the default behavior for the current process. This led to inconsistencies, such as only sometimes searching PATH or the current working directory, and OS functions such as AddDllDirectory having no effect.

In 3.8, the two primary ways DLLs are loaded now explicitly override the process-wide behavior to ensure consistency. See the porting notes for information on updating libraries.

These functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller. Errors will be reported as OSError exceptions.

The current process is replaced immediately. Open file objects and descriptors are not flushed, so if there may be data buffered on these open files, you should flush them using sys.stdout.flush() or os.fsync() before calling an exec* function.

The “l” and “v” variants of the exec* functions differ in how command-line arguments are passed. The “l” variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to the execl*() functions. The “v” variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the args parameter. In either case, the arguments to the child process should start with the name of the command being run, but this is not enforced.

The variants which include a “p” near the end ( execlp() , execlpe() , execvp() , and execvpe() ) will use the PATH environment variable to locate the program file . When the environment is being replaced (using one of the exec*e variants, discussed in the next paragraph), the new environment is used as the source of the PATH variable. The other variants, execl() , execle() , execv() , and execve() , will not use the PATH variable to locate the executable; path must contain an appropriate absolute or relative path.

For execle() , execlpe() , execve() , and execvpe() (note that these all end in “e”), the env parameter must be a mapping which is used to define the environment variables for the new process (these are used instead of the current process’ environment); the functions execl() , execlp() , execv() , and execvp() all cause the new process to inherit the environment of the current process.

For execve() on some platforms, path may also be specified as an open file descriptor. This functionality may not be supported on your platform; you can check whether or not it is available using os.supports_fd . If it is unavailable, using it will raise a NotImplementedError .

Raises an auditing event os.exec with arguments path , args , env .

3.3 sürümüyle geldi: Added support for specifying path as an open file descriptor for execve() .

Exit the process with status n , without calling cleanup handlers, flushing stdio buffers, etc.

The standard way to exit is sys.exit(n) . _exit() should normally only be used in the child process after a fork() .

The following exit codes are defined and can be used with _exit() , although they are not required. These are typically used for system programs written in Python, such as a mail server’s external command delivery program.

Some of these may not be available on all Unix platforms, since there is some variation. These constants are defined where they are defined by the underlying platform.

Exit code that means no error occurred.

Exit code that means the command was used incorrectly, such as when the wrong number of arguments are given.

Exit code that means the input data was incorrect.

Exit code that means an input file did not exist or was not readable.

Exit code that means a specified user did not exist.

Exit code that means a specified host did not exist.

Exit code that means that a required service is unavailable.

Exit code that means an internal software error was detected.

Exit code that means an operating system error was detected, such as the inability to fork or create a pipe.

Exit code that means some system file did not exist, could not be opened, or had some other kind of error.

Exit code that means a user specified output file could not be created.

Exit code that means that an error occurred while doing I/O on some file.

Exit code that means a temporary failure occurred. This indicates something that may not really be an error, such as a network connection that couldn’t be made during a retryable operation.

Exit code that means that a protocol exchange was illegal, invalid, or not understood.

Exit code that means that there were insufficient permissions to perform the operation (but not intended for file system problems).

Exit code that means that some kind of configuration error occurred.

Exit code that means something like “an entry was not found”.

Fork a child process. Return 0 in the child and the child’s process id in the parent. If an error occurs OSError is raised.

Note that some platforms including FreeBSD <= 6.3 and Cygwin have known issues when using fork() from a thread.

Raises an auditing event os.fork with no arguments.

3.8 sürümünde değişti: Calling fork() in a subinterpreter is no longer supported ( RuntimeError is raised).

See ssl for applications that use the SSL module with fork().

Fork a child process, using a new pseudo-terminal as the child’s controlling terminal. Return a pair of (pid, fd) , where pid is 0 in the child, the new child’s process id in the parent, and fd is the file descriptor of the master end of the pseudo-terminal. For a more portable approach, use the pty module. If an error occurs OSError is raised.

Raises an auditing event os.forkpty with no arguments.

3.8 sürümünde değişti: Calling forkpty() in a subinterpreter is no longer supported ( RuntimeError is raised).

Send signal sig to the process pid . Constants for the specific signals available on the host platform are defined in the signal module.

Windows: The signal.CTRL_C_EVENT and signal.CTRL_BREAK_EVENT signals are special signals which can only be sent to console processes which share a common console window, e.g., some subprocesses. Any other value for sig will cause the process to be unconditionally killed by the TerminateProcess API, and the exit code will be set to sig . The Windows version of kill() additionally takes process handles to be killed.

See also signal.pthread_kill() .

Raises an auditing event os.kill with arguments pid , sig .

3.2 sürümüyle geldi: Windows support.

Send the signal sig to the process group pgid .

Raises an auditing event os.killpg with arguments pgid , sig .

Add increment to the process’s “niceness”. Return the new niceness.

Return a file descriptor referring to the process pid . This descriptor can be used to perform process management without races and signals. The flags argument is provided for future extensions; no flag values are currently defined.

See the pidfd_open(2) man page for more details.

Availability : Linux 5.3+

3.9 sürümüyle geldi.

Lock program segments into memory. The value of op (defined in <sys/lock.h> ) determines which segments are locked.

Open a pipe to or from command cmd . The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w' . The buffering argument has the same meaning as the corresponding argument to the built-in open() function. The returned file object reads or writes text strings rather than bytes.

The close method returns None if the subprocess exited successfully, or the subprocess’s return code if there was an error. On POSIX systems, if the return code is positive it represents the return value of the process left-shifted by one byte. If the return code is negative, the process was terminated by the signal given by the negated value of the return code. (For example, the return value might be - signal.SIGKILL if the subprocess was killed.) On Windows systems, the return value contains the signed integer return code from the child process.

On Unix, waitstatus_to_exitcode() can be used to convert the close method result (exit status) into an exit code if it is not None . On Windows, the close method result is directly the exit code (or None ).

This is implemented using subprocess.Popen ; see that class’s documentation for more powerful ways to manage and communicate with subprocesses.

Wraps the posix_spawn() C library API for use from Python.

Most users should use subprocess.run() instead of posix_spawn() .

The positional-only arguments path , args , and env are similar to execve() .

The path parameter is the path to the executable file. The path should contain a directory. Use posix_spawnp() to pass an executable file without directory.

The file_actions argument may be a sequence of tuples describing actions to take on specific file descriptors in the child process between the C library implementation’s fork() and exec() steps. The first item in each tuple must be one of the three type indicator listed below describing the remaining tuple elements:

( os.POSIX_SPAWN_OPEN , fd , path , flags , mode )

Performs os.dup2(os.open(path, flags, mode), fd) .

( os.POSIX_SPAWN_CLOSE , fd )

Performs os.close(fd) .

( os.POSIX_SPAWN_DUP2 , fd , new_fd )

Performs os.dup2(fd, new_fd) .

These tuples correspond to the C library posix_spawn_file_actions_addopen() , posix_spawn_file_actions_addclose() , and posix_spawn_file_actions_adddup2() API calls used to prepare for the posix_spawn() call itself.

The setpgroup argument will set the process group of the child to the value specified. If the value specified is 0, the child’s process group ID will be made the same as its process ID. If the value of setpgroup is not set, the child will inherit the parent’s process group ID. This argument corresponds to the C library POSIX_SPAWN_SETPGROUP flag.

If the resetids argument is True it will reset the effective UID and GID of the child to the real UID and GID of the parent process. If the argument is False , then the child retains the effective UID and GID of the parent. In either case, if the set-user-ID and set-group-ID permission bits are enabled on the executable file, their effect will override the setting of the effective UID and GID. This argument corresponds to the C library POSIX_SPAWN_RESETIDS flag.

If the setsid argument is True , it will create a new session ID for posix_spawn . setsid requires POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP flag. Otherwise, NotImplementedError is raised.

The setsigmask argument will set the signal mask to the signal set specified. If the parameter is not used, then the child inherits the parent’s signal mask. This argument corresponds to the C library POSIX_SPAWN_SETSIGMASK flag.

The sigdef argument will reset the disposition of all signals in the set specified. This argument corresponds to the C library POSIX_SPAWN_SETSIGDEF flag.

The scheduler argument must be a tuple containing the (optional) scheduler policy and an instance of sched_param with the scheduler parameters. A value of None in the place of the scheduler policy indicates that is not being provided. This argument is a combination of the C library POSIX_SPAWN_SETSCHEDPARAM and POSIX_SPAWN_SETSCHEDULER flags.

Raises an auditing event os.posix_spawn with arguments path , argv , env .

Wraps the posix_spawnp() C library API for use from Python.

Similar to posix_spawn() except that the system searches for the executable file in the list of directories specified by the PATH environment variable (in the same way as for execvp(3) ).

Availability : See posix_spawn() documentation.

Register callables to be executed when a new child process is forked using os.fork() or similar process cloning APIs. The parameters are optional and keyword-only. Each specifies a different call point.

before is a function called before forking a child process.

after_in_parent is a function called from the parent process after forking a child process.

after_in_child is a function called from the child process.

These calls are only made if control is expected to return to the Python interpreter. A typical subprocess launch will not trigger them as the child is not going to re-enter the interpreter.

Functions registered for execution before forking are called in reverse registration order. Functions registered for execution after forking (either in the parent or in the child) are called in registration order.

Note that fork() calls made by third-party C code may not call those functions, unless it explicitly calls PyOS_BeforeFork() , PyOS_AfterFork_Parent() and PyOS_AfterFork_Child() .

There is no way to unregister a function.

Execute the program path in a new process.

(Note that the subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions. Check especially the Replacing Older Functions with the subprocess Module section.)

If mode is P_NOWAIT , this function returns the process id of the new process; if mode is P_WAIT , returns the process’s exit code if it exits normally, or -signal , where signal is the signal that killed the process. On Windows, the process id will actually be the process handle, so can be used with the waitpid() function.

Note on VxWorks, this function doesn’t return -signal when the new process is killed. Instead it raises OSError exception.

The “l” and “v” variants of the spawn* functions differ in how command-line arguments are passed. The “l” variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to the spawnl*() functions. The “v” variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the args parameter. In either case, the arguments to the child process must start with the name of the command being run.

The variants which include a second “p” near the end ( spawnlp() , spawnlpe() , spawnvp() , and spawnvpe() ) will use the PATH environment variable to locate the program file . When the environment is being replaced (using one of the spawn*e variants, discussed in the next paragraph), the new environment is used as the source of the PATH variable. The other variants, spawnl() , spawnle() , spawnv() , and spawnve() , will not use the PATH variable to locate the executable; path must contain an appropriate absolute or relative path.

For spawnle() , spawnlpe() , spawnve() , and spawnvpe() (note that these all end in “e”), the env parameter must be a mapping which is used to define the environment variables for the new process (they are used instead of the current process’ environment); the functions spawnl() , spawnlp() , spawnv() , and spawnvp() all cause the new process to inherit the environment of the current process. Note that keys and values in the env dictionary must be strings; invalid keys or values will cause the function to fail, with a return value of 127 .

As an example, the following calls to spawnlp() and spawnvpe() are equivalent:

Raises an auditing event os.spawn with arguments mode , path , args , env .

Availability : Unix, Windows. spawnlp() , spawnlpe() , spawnvp() and spawnvpe() are not available on Windows. spawnle() and spawnve() are not thread-safe on Windows; we advise you to use the subprocess module instead.

Possible values for the mode parameter to the spawn* family of functions. If either of these values is given, the spawn*() functions will return as soon as the new process has been created, with the process id as the return value.

Possible value for the mode parameter to the spawn* family of functions. If this is given as mode , the spawn*() functions will not return until the new process has run to completion and will return the exit code of the process the run is successful, or -signal if a signal kills the process.

Possible values for the mode parameter to the spawn* family of functions. These are less portable than those listed above. P_DETACH is similar to P_NOWAIT , but the new process is detached from the console of the calling process. If P_OVERLAY is used, the current process will be replaced; the spawn* function will not return.

Start a file with its associated application.

When operation is not specified or 'open' , this acts like double-clicking the file in Windows Explorer, or giving the file name as an argument to the start command from the interactive command shell: the file is opened with whatever application (if any) its extension is associated.

When another operation is given, it must be a “command verb” that specifies what should be done with the file. Common verbs documented by Microsoft are 'print' and 'edit' (to be used on files) as well as 'explore' and 'find' (to be used on directories).

startfile() returns as soon as the associated application is launched. There is no option to wait for the application to close, and no way to retrieve the application’s exit status. The path parameter is relative to the current directory. If you want to use an absolute path, make sure the first character is not a slash ( '/' ); the underlying Win32 ShellExecute() function doesn’t work if it is. Use the os.path.normpath() function to ensure that the path is properly encoded for Win32.

To reduce interpreter startup overhead, the Win32 ShellExecute() function is not resolved until this function is first called. If the function cannot be resolved, NotImplementedError will be raised.

Raises an auditing event os.startfile with arguments path , operation .

Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system() , and has the same limitations. Changes to sys.stdin , etc. are not reflected in the environment of the executed command. If command generates any output, it will be sent to the interpreter standard output stream. The C standard does not specify the meaning of the return value of the C function, so the return value of the Python function is system-dependent.

On Unix, the return value is the exit status of the process encoded in the format specified for wait() .

On Windows, the return value is that returned by the system shell after running command . The shell is given by the Windows environment variable COMSPEC : it is usually cmd.exe , which returns the exit status of the command run; on systems using a non-native shell, consult your shell documentation.

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

On Unix, waitstatus_to_exitcode() can be used to convert the result (exit status) into an exit code. On Windows, the result is directly the exit code.

Raises an auditing event os.system with argument command .

Returns the current global process times. The return value is an object with five attributes:

user - user time

system - system time

children_user - user time of all child processes

children_system - system time of all child processes

elapsed - elapsed real time since a fixed point in the past

For backwards compatibility, this object also behaves like a five-tuple containing user , system , children_user , children_system , and elapsed in that order.

See the Unix manual page times(2) and times(3) manual page on Unix or the GetProcessTimes MSDN on Windows. On Windows, only user and system are known; the other attributes are zero.

Wait for completion of a child process, and return a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.

waitstatus_to_exitcode() can be used to convert the exit status into an exit code.

waitpid() can be used to wait for the completion of a specific child process and has more options.

Wait for the completion of one or more child processes. idtype can be P_PID , P_PGID , P_ALL , or P_PIDFD on Linux. id specifies the pid to wait on. options is constructed from the ORing of one or more of WEXITED , WSTOPPED or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT . The return value is an object representing the data contained in the siginfo_t structure, namely: si_pid , si_uid , si_signo , si_status , si_code or None if WNOHANG is specified and there are no children in a waitable state.

These are the possible values for idtype in waitid() . They affect how id is interpreted.

This is a Linux-specific idtype that indicates that id is a file descriptor that refers to a process.

Availability : Linux 5.4+

Flags that can be used in options in waitid() that specify what child signal to wait for.

These are the possible values for si_code in the result returned by waitid() .

3.9 sürümünde değişti: Added CLD_KILLED and CLD_STOPPED values.

The details of this function differ on Unix and Windows.

On Unix: Wait for completion of a child process given by process id pid , and return a tuple containing its process id and exit status indication (encoded as for wait() ). The semantics of the call are affected by the value of the integer options , which should be 0 for normal operation.

If pid is greater than 0 , waitpid() requests status information for that specific process. If pid is 0 , the request is for the status of any child in the process group of the current process. If pid is -1 , the request pertains to any child of the current process. If pid is less than -1 , status is requested for any process in the process group -pid (the absolute value of pid ).

An OSError is raised with the value of errno when the syscall returns -1.

On Windows: Wait for completion of a process given by process handle pid , and return a tuple containing pid , and its exit status shifted left by 8 bits (shifting makes cross-platform use of the function easier). A pid less than or equal to 0 has no special meaning on Windows, and raises an exception. The value of integer options has no effect. pid can refer to any process whose id is known, not necessarily a child process. The spawn* functions called with P_NOWAIT return suitable process handles.

Similar to waitpid() , except no process id argument is given and a 3-element tuple containing the child’s process id, exit status indication, and resource usage information is returned. Refer to resource . getrusage() for details on resource usage information. The option argument is the same as that provided to waitpid() and wait4() .

waitstatus_to_exitcode() can be used to convert the exit status into an exitcode.

Similar to waitpid() , except a 3-element tuple, containing the child’s process id, exit status indication, and resource usage information is returned. Refer to resource . getrusage() for details on resource usage information. The arguments to wait4() are the same as those provided to waitpid() .

Convert a wait status to an exit code.

If the process exited normally (if WIFEXITED(status) is true), return the process exit status (return WEXITSTATUS(status) ): result greater than or equal to 0.

If the process was terminated by a signal (if WIFSIGNALED(status) is true), return -signum where signum is the number of the signal that caused the process to terminate (return -WTERMSIG(status) ): result less than 0.

Otherwise, raise a ValueError .

On Windows, return status shifted right by 8 bits.

On Unix, if the process is being traced or if waitpid() was called with WUNTRACED option, the caller must first check if WIFSTOPPED(status) is true. This function must not be called if WIFSTOPPED(status) is true.

WIFEXITED() , WEXITSTATUS() , WIFSIGNALED() , WTERMSIG() , WIFSTOPPED() , WSTOPSIG() functions.

The option for waitpid() to return immediately if no child process status is available immediately. The function returns (0, 0) in this case.

This option causes child processes to be reported if they have been continued from a job control stop since their status was last reported.

Availability : some Unix systems.

This option causes child processes to be reported if they have been stopped but their current state has not been reported since they were stopped.

The following functions take a process status code as returned by system() , wait() , or waitpid() as a parameter. They may be used to determine the disposition of a process.

Return True if a core dump was generated for the process, otherwise return False .

This function should be employed only if WIFSIGNALED() is true.

Return True if a stopped child has been resumed by delivery of SIGCONT (if the process has been continued from a job control stop), otherwise return False .

See WCONTINUED option.

Return True if the process was stopped by delivery of a signal, otherwise return False .

WIFSTOPPED() only returns True if the waitpid() call was done using WUNTRACED option or when the process is being traced (see ptrace(2) ).

Return True if the process was terminated by a signal, otherwise return False .

Return True if the process exited terminated normally, that is, by calling exit() or _exit() , or by returning from main() ; otherwise return False .

Return the process exit status.

This function should be employed only if WIFEXITED() is true.

Return the signal which caused the process to stop.

This function should be employed only if WIFSTOPPED() is true.

Return the number of the signal that caused the process to terminate.

Interface to the scheduler ¶

These functions control how a process is allocated CPU time by the operating system. They are only available on some Unix platforms. For more detailed information, consult your Unix manpages.

The following scheduling policies are exposed if they are supported by the operating system.

The default scheduling policy.

Scheduling policy for CPU-intensive processes that tries to preserve interactivity on the rest of the computer.

Scheduling policy for extremely low priority background tasks.

Scheduling policy for sporadic server programs.

A First In First Out scheduling policy.

A round-robin scheduling policy.

This flag can be OR’ed with any other scheduling policy. When a process with this flag set forks, its child’s scheduling policy and priority are reset to the default.

This class represents tunable scheduling parameters used in sched_setparam() , sched_setscheduler() , and sched_getparam() . It is immutable.

At the moment, there is only one possible parameter:

The scheduling priority for a scheduling policy.

Get the minimum priority value for policy . policy is one of the scheduling policy constants above.

Get the maximum priority value for policy . policy is one of the scheduling policy constants above.

Set the scheduling policy for the process with PID pid . A pid of 0 means the calling process. policy is one of the scheduling policy constants above. param is a sched_param instance.

Return the scheduling policy for the process with PID pid . A pid of 0 means the calling process. The result is one of the scheduling policy constants above.

Set the scheduling parameters for the process with PID pid . A pid of 0 means the calling process. param is a sched_param instance.

Return the scheduling parameters as a sched_param instance for the process with PID pid . A pid of 0 means the calling process.

Return the round-robin quantum in seconds for the process with PID pid . A pid of 0 means the calling process.

Voluntarily relinquish the CPU.

Restrict the process with PID pid (or the current process if zero) to a set of CPUs. mask is an iterable of integers representing the set of CPUs to which the process should be restricted.

Return the set of CPUs the process with PID pid (or the current process if zero) is restricted to.

Miscellaneous System Information ¶

Return string-valued system configuration values. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given as the keys of the confstr_names dictionary. For configuration variables not included in that mapping, passing an integer for name is also accepted.

If the configuration value specified by name isn’t defined, None is returned.

If name is a string and is not known, ValueError is raised. If a specific value for name is not supported by the host system, even if it is included in confstr_names , an OSError is raised with errno.EINVAL for the error number.

Dictionary mapping names accepted by confstr() to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system.

Return the number of CPUs in the system. Returns None if undetermined.

This number is not equivalent to the number of CPUs the current process can use. The number of usable CPUs can be obtained with len(os.sched_getaffinity(0))

Return the number of processes in the system run queue averaged over the last 1, 5, and 15 minutes or raises OSError if the load average was unobtainable.

Return integer-valued system configuration values. If the configuration value specified by name isn’t defined, -1 is returned. The comments regarding the name parameter for confstr() apply here as well; the dictionary that provides information on the known names is given by sysconf_names .

Dictionary mapping names accepted by sysconf() to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system.

The following data values are used to support path manipulation operations. These are defined for all platforms.

Higher-level operations on pathnames are defined in the os.path module.

The constant string used by the operating system to refer to the current directory. This is '.' for Windows and POSIX. Also available via os.path .

The constant string used by the operating system to refer to the parent directory. This is '..' for Windows and POSIX. Also available via os.path .

The character used by the operating system to separate pathname components. This is '/' for POSIX and '\\' for Windows. Note that knowing this is not sufficient to be able to parse or concatenate pathnames — use os.path.split() and os.path.join() — but it is occasionally useful. Also available via os.path .

An alternative character used by the operating system to separate pathname components, or None if only one separator character exists. This is set to '/' on Windows systems where sep is a backslash. Also available via os.path .

The character which separates the base filename from the extension; for example, the '.' in os.py . Also available via os.path .

The character conventionally used by the operating system to separate search path components (as in PATH ), such as ':' for POSIX or ';' for Windows. Also available via os.path .

The default search path used by exec*p* and spawn*p* if the environment doesn’t have a 'PATH' key. Also available via os.path .

The string used to separate (or, rather, terminate) lines on the current platform. This may be a single character, such as '\n' for POSIX, or multiple characters, for example, '\r\n' for Windows. Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.

The file path of the null device. For example: '/dev/null' for POSIX, 'nul' for Windows. Also available via os.path .

Flags for use with the setdlopenflags() and getdlopenflags() functions. See the Unix manual page dlopen(3) for what the different flags mean.

Random numbers ¶

Get up to size random bytes. The function can return less bytes than requested.

These bytes can be used to seed user-space random number generators or for cryptographic purposes.

getrandom() relies on entropy gathered from device drivers and other sources of environmental noise. Unnecessarily reading large quantities of data will have a negative impact on other users of the /dev/random and /dev/urandom devices.

The flags argument is a bit mask that can contain zero or more of the following values ORed together: os.GRND_RANDOM and GRND_NONBLOCK .

See also the Linux getrandom() manual page .

Availability : Linux 3.17 and newer.

Return a bytestring of size random bytes suitable for cryptographic use.

This function returns random bytes from an OS-specific randomness source. The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation.

On Linux, if the getrandom() syscall is available, it is used in blocking mode: block until the system urandom entropy pool is initialized (128 bits of entropy are collected by the kernel). See the PEP 524 for the rationale. On Linux, the getrandom() function can be used to get random bytes in non-blocking mode (using the GRND_NONBLOCK flag) or to poll until the system urandom entropy pool is initialized.

On a Unix-like system, random bytes are read from the /dev/urandom device. If the /dev/urandom device is not available or not readable, the NotImplementedError exception is raised.

On Windows, it will use CryptGenRandom() .

The secrets module provides higher level functions. For an easy-to-use interface to the random number generator provided by your platform, please see random.SystemRandom .

3.6.0 sürümünde değişti: On Linux, getrandom() is now used in blocking mode to increase the security.

3.5.2 sürümünde değişti: On Linux, if the getrandom() syscall blocks (the urandom entropy pool is not initialized yet), fall back on reading /dev/urandom .

3.5 sürümünde değişti: On Linux 3.17 and newer, the getrandom() syscall is now used when available. On OpenBSD 5.6 and newer, the C getentropy() function is now used. These functions avoid the usage of an internal file descriptor.

By default, when reading from /dev/random , getrandom() blocks if no random bytes are available, and when reading from /dev/urandom , it blocks if the entropy pool has not yet been initialized.

If the GRND_NONBLOCK flag is set, then getrandom() does not block in these cases, but instead immediately raises BlockingIOError .

If this bit is set, then random bytes are drawn from the /dev/random pool instead of the /dev/urandom pool.

Table of Contents

  • File Names, Command Line Arguments, and Environment Variables
  • Process Parameters
  • File Object Creation
  • Querying the size of a terminal
  • Inheritance of File Descriptors
  • Linux extended attributes
  • Process Management
  • Interface to the scheduler
  • Miscellaneous System Information
  • Random numbers

Önceki konu

Generic Operating System Services

Sonraki konu

io — Core tools for working with streams

  • Hata Bildir
  • Kaynağı Göster
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

local variable referenced before assignment with try and except statement [duplicate]

I'm having some issues with the try and except statements, I have an entry widget that takes input in strings but I have code which converts it to a integer later, problem is if the user inputs something like text it throws an error like this:

So I wanted to hide the error with the try and except statements but I now get another error message.

This is what it looks like in the code.

The new error message:

I can't figure out why this is happening and how to fix it so any help would be appreciated.

bad_coder's user avatar

4 Answers 4

To add to @alecxe's answer , I would rather modify the program like so:

Basically, what the error means is that in case of an error, entryx, entryy never get assigned anything, but still get referenced later in the if..else check.

It's best to have default values for the variables outside of the try..except block.

Community's user avatar

If there is an exception in your try/except block, there wouldn't be entryx and entryy variables defined in the scope.

You should either throw and error and exit the program or assign entryx and entryy default values in the except block.

Also, you can make a while loop until the user enters an integer like it was suggested here .

alecxe's user avatar

I would initialise answerx, answery with None before try block starts.

Lukasz's user avatar

you can see 'text' message. so, exception was raised and entryx wasn't initialized. that's why you've got:

Marcin Fabrykowski's user avatar

Not the answer you're looking for? Browse other questions tagged python try-catch or ask your own question .

  • The Overflow Blog
  • The evolution of full stack engineers
  • One of the best ways to get value for AI coding tools: generating tests
  • Featured on Meta
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • User activation: Learnings and opportunities
  • Staging Ground Reviewer Motivation
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • 4/4 time change to 6/8 time
  • Text processing: Filter & re-publish HTML table
  • Getting lost on a Circular Track
  • How much could gravity increase before a military tank is crushed
  • Undead hunger & nourishing gate?
  • Is it secure to block passwords that are too similar to other employees' old passwords?
  • Should I write an email to a Latino teacher working in the US in English or Spanish?
  • Is there mathematical significance to the LaGuardia floor tiles?
  • Was using an older version of a legal card from a nonlegal set ever not legal?
  • Does a debt exist for a Parking Charge Notice?
  • What is the rationale behind 32333 "Technic Pin Connector Block 1 x 5 x 3"?
  • Can't identify logo for a 135N68A MOSFET. Hunting for datasheet. Any ideas?
  • Does anyone know what type is screw this is?
  • When should I put a biasing resistor - op-amps
  • Please help me identify my Dad's bike collection (80's-2000's)
  • Maximize finds solution outside the constraint
  • What is the shortest viable hmac for non-critical applications?
  • Has anyone returned from space in a different vehicle from the one they went up in? And if so who was the first?
  • How would the following changes affect this monster's CR?
  • Two sisters live alone in a house after the rest of their family died
  • Is this a misstatement of Euclid in Halmos' Naive Set Theory book?
  • Can a V22 Osprey operate with only one propeller?
  • What is the least number of colours Peter could use to color the 3x3 square?
  • How can I format a partition in a mapper device?

local variable 'result' referenced before assignment python

IMAGES

  1. python

    local variable 'result' referenced before assignment python

  2. Local variable referenced before assignment Python

    local variable 'result' referenced before assignment python

  3. Local variable referenced before assignment in Python

    local variable 'result' referenced before assignment python

  4. Local variable referenced before assignment in Python

    local variable 'result' referenced before assignment python

  5. [SOLVED] Local Variable Referenced Before Assignment

    local variable 'result' referenced before assignment python

  6. [SOLVED] Local Variable Referenced Before Assignment

    local variable 'result' referenced before assignment python

VIDEO

  1. UBUNTU FIX: UnboundLocalError: local variable 'version' referenced before assignment

  2. "Mastering Assignment Operators in Python: A Comprehensive Guide"

  3. error in django: local variable 'context' referenced before assignment

  4. #6 Python Variable Assignment Part_1 (Variables in Python)

  5. Using Local Variables in LabVIEW

  6. PYTHON VARIABLES WITH IN 60 SECONDS!!! #python #coding #variables

COMMENTS

  1. Python 3: UnboundLocalError: local variable referenced before

    File "weird.py", line 5, in main. print f(3) UnboundLocalError: local variable 'f' referenced before assignment. Python sees the f is used as a local variable in [f for f in [1, 2, 3]], and decides that it is also a local variable in f(3). You could add a global f statement: def f(x): return x. def main():

  2. Fix "local variable referenced before assignment" in Python

    Reliable monitoring for your app, databases, infrastructure, and the vendors they rely on. Ping Bot is a powerful uptime and performance monitoring tool that helps notify you and resolve issues before they affect your customers.

  3. How to Fix

    Output. Hangup (SIGHUP) Traceback (most recent call last): File "Solution.py", line 7, in <module> example_function() File "Solution.py", line 4, in example_function x += 1 # Trying to modify global variable 'x' without declaring it as global UnboundLocalError: local variable 'x' referenced before assignment Solution for Local variable Referenced Before Assignment in Python

  4. Local variable referenced before assignment in Python

    If a variable is assigned a value in a function's body, it is a local variable unless explicitly declared as global. # Local variables shadow global ones with the same name You could reference the global name variable from inside the function but if you assign a value to the variable in the function's body, the local variable shadows the global one.

  5. Python local variable referenced before assignment Solution

    Trying to assign a value to a variable that does not have local scope can result in this error: UnboundLocalError: local variable referenced before assignment. Python has a simple rule to determine the scope of a variable. If a variable is assigned in a function, that variable is local. This is because it is assumed that when you define a ...

  6. UnboundLocalError Local variable Referenced Before Assignment in Python

    Avoid Reassignment of Global Variables. Below, code calculates a new value (local_var) based on the global variable and then prints both the local and global variables separately.It demonstrates that the global variable is accessed directly without being reassigned within the function.

  7. How to fix UnboundLocalError: local variable 'x' referenced before

    The UnboundLocalError: local variable 'x' referenced before assignment occurs when you reference a variable inside a function before declaring that variable. To resolve this error, you need to use a different variable name when referencing the existing variable, or you can also specify a parameter for the function. I hope this tutorial is useful.

  8. Local variable referenced before assignment in Python

    Using nonlocal keyword. The nonlocal keyword is used to work with variables inside nested functions, where the variable should not belong to the inner function. It allows you to modify the value of a non-local variable in the outer scope. For example, if you have a function outer that defines a variable x, and another function inner inside outer that tries to change the value of x, you need to ...

  9. [SOLVED] Local Variable Referenced Before Assignment

    Local Variables Global Variables; A local variable is declared primarily within a Python function.: Global variables are in the global scope, outside a function. A local variable is created when the function is called and destroyed when the execution is finished.

  10. How to Fix Local Variable Referenced Before Assignment Error in Python

    value = value + 1 print (value) increment() If you run this code, you'll get. BASH. UnboundLocalError: local variable 'value' referenced before assignment. The issue is that in this line: PYTHON. value = value + 1. We are defining a local variable called value and then trying to use it before it has been assigned a value, instead of using the ...

  11. 4 Ways to Fix Local Variable Referenced Before Assignment Error in Python

    Strategy 2: Using the Global Keyword. In Python, variables declared inside a function are considered local variables. Thus, they are separate from other variables declared outside of the function.

  12. python

    UnboundLocalError: local variable 'result' referenced before assignment. To solve this, you should define result before the for loop with a default value. In addition, it sounds like the get_response function doesn't get the values you expect (i.e intents_list 's and\or intents_json 's content is different than what you are expecting).

  13. Local Variable Referenced Before Assignment in Python: What It Is and

    Q: What are the consequences of referencing a local variable before assignment in Python? A: If you reference a local variable before assignment in Python, the following consequences may occur: The variable may contain an unexpected value. The program may crash. The program may produce incorrect results.

  14. Local Variable Referenced Before Assignment in Python

    This tutorial explains the reason and solution of the python error local variable referenced before assignment

  15. Python UnboundLocalError: local variable referenced before assignment

    UnboundLocalError: local variable referenced before assignment. Example #1: Accessing a Local Variable. Solution #1: Passing Parameters to the Function. Solution #2: Use Global Keyword. Example #2: Function with if-elif statements. Solution #1: Include else statement. Solution #2: Use global keyword. Summary.

  16. Python 3: UnboundLocalError: local variable referenced before assignment

    To fix this, you can either move the assignment of the variable x before the print statement, or give it an initial value before the print statement. def example (): x = 5 print (x) example()

  17. Local variable referenced before assignment in Python

    The "Local variable referenced before assignment" appears in Python due to assigning a value to a variable that does not have a local scope. To fix this error, the global keyword, return statement, and nonlocal nested function is used in Python script.

  18. Local (?) variable referenced before assignment

    In order for you to modify test1 while inside a function you will need to do define test1 as a global variable, for example: test1 = 0. def test_func(): global test1. test1 += 1. test_func() However, if you only need to read the global variable you can print it without using the keyword global, like so: test1 = 0.

  19. Local variable referenced before assignment? : r/learnpython

    The issue is caused by this line. attempts -= 1. In python there is a concept called scope, which is how it reads variables. By default it uses local scope, so it checks what variables are created within the function to see which are local, if it is not created in the function then it looks outside. So, you're about to say "I create both pin ...

  20. Local variable referenced before assignment?

    @HoKy22: Are you asking why dct[key] = val does not raise a "local variable referenced before assignment" error? The reason is that this is not a bare name assignment. Instead, it causes Python to make the function call dct.__setitem__(key, val). -

  21. os

    This module provides a portable way of using operating system dependent functionality. If you just want to read or write a file see open(), if you want to manipulate paths, see the os.path module, and if you want to read all the lines in all the files on the command line see the fileinput module. For creating temporary files and directories see the tempfile module, and for high-level file and ...

  22. python

    I'm having some issues with the try and except statements, I have an entry widget that takes input in strings but I have code which converts it to a integer later, problem is if the user inputs som...