Using input()
in Python 3.6 and later
username = input("Enter username: ")
print("Username is: " + username)
When you run this code, it will prompt you to enter a username and then print the entered username.
Using raw_input()
in Python 2.7
username = raw_input("Enter username: ")
print("Username is: " + username)
In Python 2.7, raw_input()
is used to read a string from standard input. This code will prompt the user to enter a username and then print the entered username.
Note: raw_input()
was renamed to input()
in Python 3. So, in Python 3, input()
performs the same function as raw_input()
in Python 2.7.
File Handling in Python | open() function in Python
How to handle files in Python, using the open()
function and the different modes available
Opening a File in Read Mode
# Open a file for reading
file = open("example.txt", "r")
print(file.read())
file.close()
This code opens example.txt
for reading and prints its contents. The file is closed after reading.
Opening a File in Append Mode
# Open a file for appending
file = open("example.txt", "a")
file.write("Appending some text.\n")
file.close()
This code opens example.txt
for appending and writes a new line at the end of the file.
Opening a File in Write Mode
# Open a file for writing
file = open("example.txt", "w")
file.write("Writing new content to the file.\n")
file.close()
This code opens example.txt
for writing. If the file already exists, it will overwrite the content.
Creating a File
# Create a new file
file = open("newfile.txt", "x")
file.write("This is a new file.\n")
file.close()
This code creates a new file named newfile.txt
. If the file already exists, an error will be raised.
Reading a File in Binary Mode
# Open a file in binary mode
file = open("image.png", "rb")
content = file.read()
file.close()
This code opens an image file in binary mode and reads its content.
Writing to a File in Text Mode
# Open a file in text mode
file = open("example.txt", "wt")
file.write("This is text mode.\n")
file.close()
This code writes to example.txt
in text mode.
Writing to a File in Binary Mode
# Open a file in binary mode
file = open("example.bin", "wb")
file.write(b"This is binary mode.")
file.close()
This code writes binary data to example.bin
.
Summary of File Modes
- “r”: Read (default mode)
- “a”: Append
- “w”: Write
- “x”: Create
- “t”: Text (default mode)
- “b”: Binary
These examples cover basic file handling operations in Python using the open()
function with different modes.
Read Files in python
More examples for Read files in Python:
Reading the Entire File
# Open and read the entire file
f = open("demofile.txt", "r")
print(f.read())
f.close()
# Open and read the entire file from a specific path
f = open("D:\\myfiles\\welcome.txt", "r")
print(f.read())
f.close()
Reading a Specific Number of Characters
# Open and read the first 5 characters of the file
f = open("demofile.txt", "r")
print(f.read(5))
f.close()
Reading One Line at a Time
# Open and read the first line of the file
f = open("demofile.txt", "r")
print(f.readline())
f.close()
# Open and read the first two lines of the file
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
f.close()
Reading the File Line by Line Using a Loop
# Open and read the file line by line using a loop
f = open("demofile.txt", "r")
for x in f:
print(x)
f.close()
These examples demonstrate how to use the open()
function to read files in different ways, utilizing methods such as read()
, readline()
, and iterating through the file line by line.
Write/Create Files in Python
More examples for Read files in Python:
Appending to a File
# Open the file in append mode and write content
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
# Open and read the file after appending
f = open("demofile2.txt", "r")
print(f.read())
f.close()
Writing to (Overwriting) a File
# Open the file in write mode and write content, which overwrites any existing content
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
# Open and read the file after writing
f = open("demofile3.txt", "r")
print(f.read())
f.close()
These examples demonstrate how to use the open()
function with different modes ("a"
for appending and "w"
for writing) to write content to files in Python. The files are then read to show the results of the write operations.
Create a New File
Using Mode "x"
(Create)
# This will create a new file, and return an error if the file already exists
try:
f = open("myfile.txt", "x")
f.write("This is a new file created using 'x' mode.")
f.close()
except FileExistsError:
print("The file already exists.")
Using Mode "a"
(Append)
# This will create a new file if it does not exist, or append to an existing file
f = open("myfile.txt", "a")
f.write("This content is appended if the file exists, or a new file is created if it does not.")
f.close()
Using Mode "w"
(Write)
# This will create a new file if it does not exist, or overwrite the existing file
f = open("myfile.txt", "w")
f.write("This content overwrites any existing content, or a new file is created if it does not exist.")
f.close()
These examples demonstrate how to use the open()
function with different modes ("x"
, "a"
, and "w"
) to create files in Python. The modes "a"
and "w"
will create a file if it does not exist, while the mode "x"
will create a file and raise an error if the file already exists.
Delete Files in Python
Delete Files in Python
To delete a file, you must import the os
module and use the os.remove()
function. You can also use os.rmdir()
to remove an empty directory.
import os
# Remove a file
os.remove("demofile.txt")
# Remove a directory
os.rmdir("myfolder")
# Check if a file exists before removing it
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
These examples cover the basics of creating, writing, and deleting files in Python, as well as handling file operations securely by checking for the existence of files before attempting to delete them.