User Inputs and File Handling
User Input¶
Python allows users to get a user input using the input() method
pangalan = input("Ano ang iyong pangalan?")
print("Ikaw ay si {}".format(pangalan))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 filestwo 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).
# Create a sample text file representing a list of farms
filename = "barangay_farms.txt"
with open(filename, "w") as f:
f.write("Farm_ID,Crop,Hectares\n")
f.write("001,Palay,2.5\n")
f.write("002,Corn,1.0\n")
f.write("003,Coconut,5.0\n")
f.write("004,Mango,3.2\n")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).
# Reading the file line by line
with open(filename, "r") as f:
# Loop through each line in the file
for line in f:
# .strip() removes the invisible newline character (\n) at the end
print(line.strip())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).
import json
import urllib.request
# URL to a sample GeoJSON
url = "https://github.com/opengeos/datasets/releases/download/world/world_cities.geojson"
try:
# 1. Open the URL
with urllib.request.urlopen(url) as response:
# 2. Read and Parse the JSON
data = json.loads(response.read().decode())
# 3. Explore the Data
feature_count = len(data['features'])
first_state = data['features'][0]['properties']['name']
print(f"Type: {data['type']}")
print(f"Total Features: {feature_count}")
print(f"First Feature Name: {first_state}")
except urllib.error.URLError as e:
print(f"Connection Error: {e}")Output
Type: FeatureCollection
Total Features: 1249
First Feature Name: Bombo