0% found this document useful (0 votes)
4 views8 pages

Python Notes

The document provides an overview of the sys module in Python, detailing its functionalities such as accessing command-line arguments, managing the Python path, and handling standard streams. It also covers file handling techniques in Python, including reading and writing text and numbers, as well as working with CSV files using the csv module. Key examples illustrate how to use these features effectively in Python programming.

Uploaded by

32gvlin1990
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views8 pages

Python Notes

The document provides an overview of the sys module in Python, detailing its functionalities such as accessing command-line arguments, managing the Python path, and handling standard streams. It also covers file handling techniques in Python, including reading and writing text and numbers, as well as working with CSV files using the csv module. Key examples illustrate how to use these features effectively in Python programming.

Uploaded by

32gvlin1990
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

MANAGING DIRECTORIES: SYS MODULE

Definition and Usage

The sys module provides access to system-specific parameters and functions that interact
with the Python interpreter.

Use it to access command-line arguments, control the Python path, exit programs, or query
interpreter settings.

Example: Get Python version and command-line arguments:


import sys

print(f'Python version: {[Link]}')


print(f'Platform: {[Link]}')

Key features and functionalities of the sys module:


 Command-line arguments:
[Link] is a list containing the command-line arguments passed to a Python script. The first
element ([Link][0]) is the script's name.

 Exiting the interpreter:


[Link](status) can be used to exit the Python interpreter with an optional exit status code.

 Python path:
[Link] is a list of strings specifying the search path for modules. Modifying this list can affect where
the interpreter looks for imported modules.
 Interpreter version:
[Link] provides a string containing information about the Python interpreter's version.

 Standard streams:
[Link], [Link], and [Link] are file-like objects representing the standard input, output, and
error streams, respectively. These can be redirected for various purposes, such as logging or custom
input/output handling.
 Recursion limit:
[Link]() returns the current maximum depth for Python's recursion,
and [Link](limit) allows setting a new limit.

 Module information:
[Link] is a dictionary that maps module names to already loaded modules, useful for introspection
or dynamic module management.
 Platform information:
[Link] returns a string identifying the platform the code is running on (e.g., 'linux', 'win32',
'darwin').

Example usage:
Python
import sys

# Accessing command-line arguments


print("Arguments passed to the script:", [Link])

# Printing Python version information


print("Python Version:", [Link])

# Redirecting standard output to a file (temporary)


original_stdout = [Link]
with open("[Link]", "w") as f:
[Link] = f
print("This message will be written to [Link]")
[Link] = original_stdout # Restore original stdout

# Exiting the program


# [Link](0) # Uncomment to exit the program

READING/WRITING TEXT AND NUMBERS


Python offers straightforward methods for reading and writing text and numbers to files. The core of file
handling in Python revolves around the open() function, which returns a file object, and various methods
associated with that object.

1. Opening Files:
The open() function takes the filename and the mode as arguments:
Python
file_object = open("[Link]", "mode")

Common modes include:


 "r": Read mode (default).
 "w": Write mode. Creates a new file or truncates (overwrites) an existing one.
 "a": Append mode. Adds data to the end of an existing file or creates a new one.
 "x": Exclusive creation mode. Creates a new file, but raises an error if it already exists.
 "t": Text mode (default).
 "b": Binary mode.

It is recommended to use the with statement for file handling, as it ensures the file is automatically
closed, even if errors occur:
Python
with open("[Link]", "r") as file_object:
# Operations on file_object

2. Writing Text and Numbers:


 write(string): Writes a string to the file. Numbers must be converted to strings before writing.
Python
with open("[Link]", "w") as f:
[Link]("This is a line of text.\n")
number = 123
[Link](str(number) + "\n")

 writelines(list_of_strings): Writes a list of strings to the file. Each string in the list is typically a
line, and you need to include newline characters (\n) if you want them on separate lines.
Python
lines = ["First line\n", "Second line\n"]
with open("[Link]", "a") as f:
[Link](lines)

3. Reading Text and Numbers:


 read(): Reads the entire content of the file as a single string.
Python
with open("[Link]", "r") as f:
content = [Link]()
print(content)

 readline(): Reads a single line from the file.


Python
with open("[Link]", "r") as f:
line1 = [Link]()
line2 = [Link]()
print(line1, line2)

 readlines(): Reads all lines from the file and returns them as a list of strings, where each string
represents a line.
Python
with open("[Link]", "r") as f:
all_lines = [Link]()
for line in all_lines:
print([Link]()) # .strip() removes leading/trailing whitespace,
including '\n'
 Iterating directly over the file object: This is an efficient way to process files line by line.
Python
with open("[Link]", "r") as f:
for line in f:
print([Link]())

4. Handling Numbers:
When reading numbers from a file, they are initially read as strings. You need to convert them to
numerical types (e.g., int(), float()) for calculations.
Python
with open("[Link]", "r") as f:
for line in f:
try:
number = int([Link]())
print(f"Read integer: {number}")
except ValueError:
print(f"Could not convert '{[Link]()}' to an integer.")

FROM/TO A FILE
File handling in Python involves reading data from a file and writing data to a file. This is typically done
using the built-in open() function, which returns a file object.

Reading From a File


To read from a file, open it in read mode ("r").
Python
# Open a file in read mode
with open("[Link]", "r") as file:
content = [Link]() # Read the entire file content as a single string
print(content)

# Alternatively, read line by line


with open("[Link]", "r") as file:
for line in file:
print([Link]()) # Process each line, removing trailing newline
characters

Writing To a File
To write to a file, open it in write mode ("w") or append mode ("a").
 "w" (write mode):

Creates a new file if it doesn't exist, or overwrites the existing file if it does.
 "a" (append mode):
Creates a new file if it doesn't exist, or appends new data to the end of an existing file.
Python
# Write to a file (overwrites if file exists)
with open("[Link]", "w") as file:
[Link]("Hello, Python!\n")
[Link]("This is a new line.\n")

# Append to a file (adds to the end)


with open("[Link]", "a") as file:
[Link]("Appending more content.\n")

Key Considerations:
 with open(...) as file::

This is the recommended way to handle files as it ensures the file is automatically closed, even if errors
occur.

 File Modes:
Choose the appropriate mode ("r", "w", "a", "x" for exclusive creation, "r+" for read/write, etc.) based
on your needs.

 Newlines:
Remember to include \n characters for line breaks when writing to a file if you want the content to
appear on separate lines.

 Error Handling:
In production code, consider adding try-except blocks to handle potential FileNotFoundError or other
file-related exceptions.
CREATING AND READING A FORMATTED FILE (CSV, TAB-SEPARATED, ETC.).

CSV (Comma Separated Values) format is one of the most widely used formats for
storing and exchanging structured data between different applications, including databases
and spreadsheets. CSV files store tabular data, where each data field is separated by a
delimiter, typically a comma. Python provides built-in support for handling CSV files
through the csv module, making it easy to read, write and manipulate CSV data efficiently.
However, we first need to import the module using:
import csv
Reading a CSV File in Python
To read a CSV file, Python provides the [Link] class, which reads data in a structured
format. The first step involves opening the CSV file using the open() function in read mode
('r'). The [Link]() function then reads the file, returning an iterable reader object.
Example CSV File: [Link]

.CSV file

Syntax:
[Link](csvfile, dialect='excel', **fmtparams)
Parameters:
 csvfile: The file object containing CSV data.
 dialect: Defines a set of parameters to control CSV reading (default is 'excel').
 **fmtparams: Additional formatting parameters like delimiter, quotechar, etc.
Example:

import csv

# Opening the CSV file


with open('[Link]', mode='r') as file:
# Reading the CSV file
csvFile = [Link](file)

# Skipping the header (uncomment if needed)


# next(csvFile)

# Displaying the contents of the CSV file


for line in csvFile:
print(line)
Output
['Steve', 13, 'A']
['John', 14, 'F']
['Nancy', 14, 'C']
['Ravi', 13, 'B']
Explanation: The csv module reads [Link] using [Link](file), iterating row by
row. The with statement ensures proper file closure. Each row is returned as a list of
column values. Use next(csvFile) to skip the header.
Writing to a csv file in python
Python provides the [Link] class to write data to a CSV file. It converts user data into
delimited strings before writing them to a file. While opening the file, using newline=''
prevents unnecessary newlines when writing.
Syntax:
[Link](csvfile, dialect='excel', **fmtparams)
Parameters:
 csvfile: The file object where CSV data will be written.
 dialect: Defines a set of parameters to control CSV writing (default is 'excel').
 **fmtparams: Additional formatting options such as delimiter, quotechar,etc.
Writing a single row:
writerow(fields)
Writing multiple rows:
writerows(rows)
Example:
import csv

# Field names
f = ['Name', 'Branch', 'Year', 'CGPA']

# Data rows of CSV file


r = [
['Nikhil', 'COE', '2', '9.0'],
['Sanchit', 'COE', '2', '9.1'],
['Aditya', 'IT', '2', '9.3'],
['Sagar', 'SE', '1', '9.5'],
['Prateek', 'MCE', '3', '7.8'],
['Sahil', 'EP', '2', '9.1']
]

# Name of the CSV file


fn = "university_records.csv"

# Writing to CSV file


with open(fn, 'w', newline='') as csvfile:
# Creating a CSV writer object
csvwriter = [Link](csvfile)

# Writing the field names


[Link](f)

# Writing the data rows


[Link](r)
Output: A file named university_records.csv will be created containing the following
data.

Output
Explanation: This example shows how to write a list of dictionaries to a CSV file
using [Link]. Each dictionary is a student record, with fieldnames as column
headers. The file is opened in write mode ('w'), writeheader() writes headers
and writerows(d) writes records.
Writing a dictionary to a csv file
The [Link] class allows writing a dictionary to a CSV file. It maps dictionary keys to
field names.
Syntax:
[Link](csvfile, fieldnames, restval='', extrasaction='raise', dialect='excel', *args,
**kwds)
Parameters:
 csvfile: The file object where CSV data will be written.
 fieldnames: A list of column headers that correspond to dictionary keys.
 restval: Default value for missing dictionary keys.
 extrasaction: Defines how to handle extra keys ('raise' or 'ignore').
 dialect: Defines a set of parameters to control CSV writing (default is 'excel').
Methods:
 writeheader(): Writes column headers using the field names.
 writerows(mydict): Writes multiple dictionary rows.
Example: A file named university_records.csv will be created containing the following
data.

import csv

# Data rows as dictionary objects


d=[
{'name': 'Nikhil', 'branch': 'COE', 'year': '2', 'cgpa': '9.0'},
{'name': 'Sanchit', 'branch': 'COE', 'year': '2', 'cgpa': '9.1'},
{'name': 'Aditya', 'branch': 'IT', 'year': '2', 'cgpa': '9.3'},
{'name': 'Sagar', 'branch': 'SE', 'year': '1', 'cgpa': '9.5'},
{'name': 'Prateek', 'branch': 'MCE', 'year': '3', 'cgpa': '7.8'},
{'name': 'Sahil', 'branch': 'EP', 'year': '2', 'cgpa': '9.1'}
]

# Field names
f = ['Name', 'Branch', 'Year', 'CGPA']

# Name of the CSV file


fn = "university_records.csv"

# Writing to CSV file


with open(fn, 'w', newline='') as csvfile:
# Creating a CSV DictWriter object
writer = [Link](csvfile, fieldnames=f)

# Writing headers (field names)


[Link]()

# Writing data rows


[Link](d)
Output

Output

Explanation: This example demonstrates writing a list of student records to a CSV file
using [Link]. The file is opened in write mode ('w'), fieldnames define column
headers, writeheader() writes them and writerows(d) adds records. Keys must match
fieldnames to ensure alignment.

You might also like