Python File Handling Basics for Beginners

day 12 python series 📂 Python File Handling – Simple Guide for Beginners File handling allows Python programs to store, read, and modify data in files instead of keeping everything in memory. It is commonly used in: Data processing Log storage Configuration files Saving user input 1️⃣ open() – Open a File The open() function is used to open a file before performing any operation. Syntax file = open("example.txt", "mode") Modes Mode Meaning r Read file w Write file (overwrite) a Append data x Create new file b Binary mode Example file = open("data.txt", "r") 2️⃣ read() – Read File Content Used to read data from a file. Example file = open("data.txt", "r") content = file.read() print(content) file.close() Other read methods file.readline() # read one line file.readlines() # read all lines as list 3️⃣ write() – Write Data to File Used to add new data to a file. ⚠ If file exists → it will overwrite old content file = open("data.txt", "w") file.write("Hello Python") file.close() 4️⃣ append() – Add Data Without Deleting Old Data Append mode adds content at the end of the file. file = open("data.txt", "a") file.write("\nLearning File Handling") file.close() Result inside file: Hello Python Learning File Handling 5️⃣ close() – Close the File Always close the file after using it to free system resources. file.close() Better method 👇 with open("data.txt", "r") as file: print(file.read()) File automatically closes. json we use dump for w and r load Write JSON File import json data = {"name": "Prem", "skill": "Machine Learning"} with open("data.json", "w") as file: json.dump(data, file) Read JSON File import json with open("data.json", "r") as file: data = json.load(file) print(data["name"]) text ->plain text json ->structure data storage more information follow Prem chandar #Python #PythonProgramming #FileHandling #JSON #CodingForBeginners #DataEngineering #MachineLearning #AI #LearnToCode #PythonDeveloper #network #connect #brand

To view or add a comment, sign in

Explore content categories