Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

User Inputs and File Handling

User Input

Python allows users to get a user input using the input() method

Output
Ano ang iyong pangalan? Juan
Ikaw ay si Juan

Files

Aside from standard inputs, Python has several functions for creating, reading, updating, and deleting files.

  • open(): key function for working with files

  • two parameters

    • filename

    • mode

      • “r” - Read - Default value. Opens a file for reading, error if the file does not exist

      • “a” - Append - Opens a file for appending, creates the file if it does not exist

      • “w” - Write - Opens a file for writing, creates the file if it does not exist

      • “x” - Create - Creates the specified file, returns an error if the file exists

    • you can also can specify if the file should be handled as binary or text mode

      • “t” - Text - Default value. Text mode

      • “b” - Binary - Binary mode (e.g. images)

Creating a file

First, let’s create a dummy dataset to work with. We use the open() function with mode 'w' (write).

  • 'w': Write (Overwrites the file if it exists).

  • 'a': Append (Adds to the end of the file).

Working with files

Now, let’s read the file we just created. The best practice is to use the with statement, it automatically closes the file even if your code crashes.

  • 'r': Read (Default mode).

Output
Farm_ID,Crop,Hectares
001,Palay,2.5
002,Corn,1.0
003,Coconut,5.0
004,Mango,3.2

Reading data from a the

Python can read data directly from the web. This is crucial for accessing modern APIs or cloud-stored data.

We will use the standard json and urllib libraries to fetch a GeoJSON file (a map file format).

Output
Type: FeatureCollection
Total Features: 1249
First Feature Name: Bombo