تلخيص List + File
تلخيص List + File
In Python, the open() function is used to open a file and return a file object. This file object
allows you to read, write, or manipulate the file contents.
Returns a handle open() returns a “file filename is a string Mode is optional and should
use to manipulate handle” - a variable be 'r' if we are planning to
the file used to perform read the file and 'w' if we are
operations on the file going to write to the file
Parameters
1. filename: A string that represents the name of the file to be opened. This can include a
relative or absolute path.
2. mode: A string that specifies the mode in which the file is opened. Some common
modes include:
o 'r': Read mode (default) - Opens the file for reading.
o 'w': Write mode - Opens the file for writing (overwrites the file if it exists).
# Open a file for reading # Open a file for writing
…. file.write('Hello, World!')
…… file.close()
file.close()
``
Output
File test.txt contents:افرض ان لديك الملف التالي ويحتوي المبف على ما يلي
Making it easy to understand. Therefore, Python is recommended as the first programming language.
I love Python
Code Output
fhand = open('test.txt') <_io.TextIOWrapper الحالة االفتراضيه لفتح
print(fhand) name='mbox.txt' الملف هي القراءة
mode='r'
encoding='UTF-8'>
Making it easy to
understand. Therefore,
Python is recommended
as the first programming
language.
I love Python
file1 = open("mbox.txt", "r") Python is a general- طباعه اول سطر من
print(file1.readline()) purpose, high-level. الملف
``
file1 = open("mbox.txt", "r") Python is البدأ في المبف من
print(file1.read(9)) البداية حتى الحرف
التاسع
file1 = open("mbox.txt", "r") a general-purpose, high- Seek(10)
file1.seek(10) level. تعني البدأ في الملف
print(file1.read()) Python was developed ابتداءا من الحرف
by Guido Van Rossum in العاشر
1989.
Making it easy to
understand. Therefore,
Python is recommended
as the first programming
language.
I love Python
file1 = open("mbox.txt", "r") a gener البدأ من الحرف العاشر
file1.seek(10) ومن ثم اخذ سبع
print(file1.read(7)) حروف فقط ابتداءا من
الحرف العاشر
fhand = open('mbox.txt') Line Count: 5 عدد االسطر داخل
count = 0 الملف
for line in fhand: يتم حساب السطر
count = count + 1 الفارغ
print('Line Count:', count)
``
There were 4 Python
Words فيPython عدد كلمات
fhand = open('mbox.txt') الملف
count = 0
for line in fhand:
if 'Python' in line:
count = count + 1
print('There were', count, 'Python Words')
OUTPUT 2
file1 = open("file1.txt", "w") Output of Read function تعني سطر جديدn\
L = "This is Amman\n", "This is Paris\n", "This is is L = "This is Amman\n",
London\n" Hello "This is Paris\n", "This
This is Amman "is London\n
file1.write("Hello \n") This is Paris
file1.writelines(L) This is London
file1.close()
file1 = open("file1.txt", "r") Output of Readline
print("Output of Read function is ") function is
print(file1.read()) Hello
print()
file1 = open("mbox1.txt", "r")
print("Output of Read function is ") Output of Read(9)
print(file1.read()) function is
print() Hello
file1.seek(0) Th
print("Output of Readline function is ")
print(file1.readline()) Output of Readline(9)
print() function is
file1.seek(0) Hello
print("Output of Read(9) function is ")
print(file1.read(9))
print()
file1.seek(0)
print("Output of Readline(9) function is ")
print(file1.readline(9))
``
Multiple Choice
1. What is the default mode of the open() function?
a) 'r' ✔
b) 'w'
c) 'a'
d) 'rb'
2. What does the 'w' mode do in the open() function?
a) Opens a file for reading only
b) Opens a file for writing and truncates it ✔
c) Appends data to a file
d) Reads the file in binary mode
3. What happens if you try to open a non-existent file in 'r' mode?
a) Creates the file
b) Returns None
c) Raises a FileNotFoundError ✔
d) Opens an empty file
4. What function is used to open a file in Python?
a) file.open()
b) open() ✔
c) read_file()
d) file()
``
6. Which mode should you use to read a file?
a) 'w'
b) 'r' ✔
c) 'rw'
d) 'x'
7. What character is used to represent a newline in strings?
a) \\
b) \n ✔
c) \t
d) \s
8. What happens if you try to open a file that does not exist?
a) The program ignores it.
b) It throws a FileNotFoundError. ✔
c) It creates a new file.
d) None of the above.
True or False
1. A file handle can be used to manipulate files.
True
Explanation: A file handle is an object returned by the open() function, which allows
operations like reading, writing, or appending to the file.
2. Using rstrip() removes whitespace and newline characters from the end of a string.
True
Explanation: The rstrip() method removes trailing whitespace and newline characters (\n)
from the end of a string.
3. The continue statement in a loop skips the current iteration and moves to the next.
True
Explanation: The continue statement allows the loop to skip the rest of the code for the
current iteration and move to the next iteration.
4. To iterate through each line of a file, you can use a for loop.
True
``
5. The input() function is used to prompt for a filename at runtime.
True
Writing Code
1. Write a python program that gets three names from the user and writes them to a file.
2.Write a python program that prompts the user for sales amounts and writes those amounts to the
sales.txt file.
``
3. Write a Python program that performs various tasks on a file entered by the user with
validation and exception handling, Tasks are :
a) Read file content.
b) Convert file contents to uppercase.
c) Count the occurrences of the letter 'I'.
d) Replace the word ‘Python’ with 'C#'.
e) Extract and print the substring 'C#'.
f) Extract and print line count
``
4. Write a Python program that will perform the following actions:
1. File Input: The program should first prompt the user to enter the name of the input text
file.
2. File Validation: Your program must check if the file exists. If the file does not exist, it
should print an informative error message and terminate gracefully.
3. Read and Process: If the file exists, read the contents of the file line by line.
String Manipulation Tasks (Apply to each line): For each line of text in the file, perform
these actions in the specified order:
4. Remove Leading/Trailing Whitespace: Remove any whitespace characters (spaces, tabs,
newlines) from the beginning and the end of the line.
5. Convert to Lowercase: Convert the entire line to lowercase.
6. Count Vowels: Calculate the number of vowels (‘a’, ‘e’, ‘I’, ‘o’, ‘u’) in the line.
7. Reverse the Line: Reverse the characters in the line.
8. Output: For each line processed, print the following, each on a new line:
o The original line as it was read from the file (before any processing).
o The processed line with whitespace removed and converted to lowercase.
o The vowel count for the processed line.
o The reversed version of the processed line.
9. Closing: Ensure that the file is properly closed after reading is complete.
``
5. Write a Python code that fulfills the requirement of taking multiple student marks, then saves the
maximum, minimum, and average marks to a file.
1. Function : calculate_and_save_marks(filename).
o Initialization: Initializes an empty list marks to store the marks entered by the
user.
o Input Loop:
Uses a while True loop to continuously prompt the user to enter marks.
Checks for the "done" input to end mark entry.
Tries to convert input to a float to accept fractional marks. If a non-
number is entered, handles the ValueError exception
Appends valid numbers to the marks list.
o Empty Mark List Check: After input is finished, verifies that at least one
mark was entered. If the list is empty, a message is printed and function exits.
o Calculations: Computes max_mark, min_mark, and average_mark.
o File Writing:
Opens the specified filename in write mode.
Writes the calculated maximum, minimum, and average to the file.
Error Handling: Uses try-except to catch potential file system errors
Prints a success or an error message.
2. Main:
o This block ensures the code inside is only executed when the script is run
directly.
o It prompts the user for the name of the output file.
o Calls the function to process the data.
Example:
Enter the name of the output file: results.txt
Enter a student's mark (or 'done' to finish): 85
Enter a student's mark (or 'done' to finish): 78.5
Enter a student's mark (or 'done' to finish): 92
Enter a student's mark (or 'done' to finish): 60
Enter a student's mark (or 'done' to finish): done
Results saved to 'results.txt' successfully.
Content of results.txt:
Maximum Mark: 92.0
Minimum Mark: 60.0
Average Mark: 78.88
``
``
6. Write program to save three students' names with their grades in mid-exam in text file
the name of text file is "mid_python.txt" They are (Yazan, 28), (Laila, 25), (Ahmad, 20)
calculate and print the average for the mid exam.
Input Example:
CODE:
``
LIST
• In Python, a list is a built-in data structure that allows you to store multiple items in a
single variable.
• Ordered: Items are stored in a specific order, and that order is preserved.
• Mutable: You can modify the items in a list (e.g., add, remove, or change items).
يمكن تعديل عناصرها
• Heterogeneous: They can store items of different data types (e.g., integers, strings, or
other lists).A list can be empty
يمكن ان تحتوي على انواع مختلفة من البيانات
• A collection allows us to put many values in a single “variable”
• A collection is nice because we can carry all many values around in one convenient
package.
•
Syntax
To create a list, use square brackets []:
my_list = [1, 2, 3, 4, 5]
Examples of Common Operations
1. Creating Lists طريقة االنشاء
empty_list = []
numbers = [1, 2, 3, 4]
mixed_list = [1, "hello", 3.14, True]
nested_list = [1, [2, 3], 4]
2. Accessing Elements الوصل الى عنصر في القائمة
Use indices (starting from 0): تبدأ القائمة من العنصر رقم صفر
numbers = [10, 20, 30, 40]
``
print(numbers[0]) # Output: 10
print(numbers[-1]) # Output: 40 (last element)
3. Modifying Elements تعديل اي عنصر باستخدام موقع العنثر داخل القائمة
numbers[1] = 25
print(numbers) # Output: [10, 25, 30, 40]
4. Adding Elements إضافة عنصر جديد الى القائمة ويتم اضافته تلقائيا في
النهاية
Append to the end:
numbers.append(50)
print(numbers) # Output: [10, 25, 30, 40, 50]
Insert at a specific position
إضافة عنصر في موقع محدد
numbers.insert(1, 15)
print(numbers) # Output: [10, 15, 25, 30, 40, 50]
5. Removing Elements
By value: حذف عنصر من باستخدام القيمة
numbers.remove(25)
print(numbers) # Output: [10, 15, 30, 40, 50]
By index:حذف عنصر باستخدام الموقع
numbers.pop(2)
print(numbers) # Output: [10, 15, 40, 50]
Clear all elements: حذف جميع العناصر
numbers.clear()
print(numbers) # Output: []
6. Iterating Through Lists
loopالتعامل مع القائمة باستخدام ال
for num in [10, 20, 30]:
print(num)
``
#output [10,20,30]
OUTPUT
my_list1 = list((1, 2, 3)) [1, 2, 3]
print(my_list1)
my_list2 = [1, 2, 3] [1, 2, 3]
print(my_list2)
my_list3 = [1.0, 'Jessa', 3] [1.0, 'Jessa', 3]
print(my_list3)
my_list4 = list() []
print(my_list4)
my_list = [1, 2, 3] 3 عدد عناصر
print(len(my_list)) list
my_list = [10, 20, 'Jessa', 12.50, 'Emma'] 20
print(my_list[1]) 'Emma'
print(my_list[4])
my_list = [10, 20, 'Jessa', 12.50, 'Emma'] 'Emma' ] تعني اخر1-[
# accessing last element of the list 12.5 list عنصر في
print(my_list[-1]) العنصر االخير 20
# output 'Emma'
my_list = [5, 8, 'Tom', 7.50, 'Emma'] [5, 8, 'Tom', 7.5] من البداية الى
# slice first four items العنصر الرابع
print(my_list[:4])
my_list = [5, 8, 'Tom', 7.50, 'Emma'] [5, 'Tom', 'Emma'] من البدايه الى
# print every second element النهاية مع
اهمال اعنصر
``
# with a skip count 2 في كل2 رقم
print(my_list[::2]) مره ودوره
جديده
``
my_list = [5, 8, 'Tom', 7.50, 'Emma'] ['Emma', 7.5, 'Tom', 8, 5] عكس
# reversing the list list عناصر
print(my_list[::-1])
my_list = [5, 8, 'Tom', 7.50, 'Emma'] [7.5, 'Emma'] من العنصر
# Without end_value الثالث الى
# Stating from 3nd item to last item النهاية
print(my_list[3:])
Iterating a List
my_list = [5, 8, 'Tom', 7.50, 'Emma'] 5
iterate a list # 8
:for item in my_list Tom
print(item) 7.5
Emma
)(Using insert #
insert 25 at position 2 #
my_list.insert(2, 25)
print(my_list)
``
Output [5, 8, 25, 'Tom', 7.5] #
print(my_list)
Output [4, 16, 36, 64] #
my_list = list([2, 4, 6, 8, 10, 12]) ]12 ,10 ,4 ,2 [
remove item 6 #
my_list.remove(6)
remove item 8 #
my_list.remove(8)
print(my_list)
Output [2, 4, 10, 12] #
``
my_list = list([6, 4, 6, 6, 8, 12]) ]12 ,8 ,4 [ حذف كل
العناصر التي
:for item in my_list قمينها
my_list.remove(6) 6 تساوي
print(my_list)
Output [4, 8, 12] #
my_list = list([2, 4, 6, 8, 10, 12]) ]12 ,4 ,2 [
Using + operator #
my_list3 = my_list1 + my_list2
print(my_list3)
my_list1 = [1, 2, 3] ]1,2,3 [
Using = operator #
new_list = my_list1
printing the new list #
print(new_list)
Output [1, 2, 3] #
``
my_list1 = [1, 2, 3] ]66 ,3 ,2 ,1 [
making changes in the original list #
my_list1.append(66)
print(my_list1)
mylist = [3,2,1] ]3 ,2 ,1 [ ترتيب
)(mylist.sort عناصر
print(mylist)
mylist = [3, 4, 5, 6, 1] ]3 ,4 ,5 ,6 ,1 [ عكس
)(mylist.reverse العناصر
print(mylist)
mylist = [3, 4, 5, 6, 1] 6
print(max(mylist)) #returns the maximum 1
.number in the list
print(min(mylist)) #returns the minimum
.number in the list
mylist = [3, 4, 5, 6, 1] 19 مجموع
print(sum(mylist)) العناصر
creating even list for a range of numbers # ]8 ,6 ,4 ,2 ,0 [ list انشاء
][ = squarelist1 للعناصر
:for s in range(10) الزوجية
:if s%2 == 0 من صفر
squarelist1.append(s) الى تسعة
print(squarelist1)
creating even square list for a range of # ]64 ,36 ,16 ,4 ,0 [ list انشاء
numbers لتربيع
][ = squarelist1 العناصر
:for s in range(10) من صفر
:if s%2 == 0 الى تسعه
squarelist1.append(s ** 2)
print(squarelist1)
``
Operation Description
List slicing with step. Returns a List with the items from
l1[i:j:k] index i up to index j taking every k-th item. An
example l1[0:4:2] is [10, 30].
``
Operation Description
Returns the item with maximum value from a list. The answer
max(l1)
is 60.
``
Multiple Choices
1. What is a characteristic of a list in Python?
a. Lists cannot be modified after creation.
c. Lists are mutable and can store elements of different types. Answer: c
``
5. Which of the following commands will create a list?
a. list1 = list()
b. list1 = []
c. list1 = list([1, 2, 3])
d. all of the mentioned Answer: d
6. What is the output when we execute list(“hello”)?
a. [‘h’, ‘e’, ‘l’, ‘l’, ‘o’] Answer: a
b. [‘hello’]
c. [‘llo’]
d. [‘olleh’]
7. Suppose list1 is [4, 2, 2, 4, 5, 2, 1, 0], Which of the following is correct syntax for slicing
operation?
a. print(list1[2:])
b. print(list1[:2])
c. print(list1[:-2])
d. all of the mentioned answer: d
8. Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1]?
a. Error
b. None
c. 25 answer: c
d. 2
9. Suppose list1 is [2, 33, 222, 14, 25], What is list1[:-1]?
a. [2, 33, 222, 14] answer: a
b. Error
c. 25
d. [25, 14, 222, 33, 2]
True or False
a. A list in Python can contain elements of different data types.
Answer: True
b. Strings in Python are mutable, just like lists.
Answer: False
c. The split() function breaks a string into a list of words.
Answer: True
d. The len() function can be used on both lists and strings.
Answer: True
``
Coding
1. Basic List Operations
Write a Python program to create a list from user input and perform the following:
o Add items to the list using the append() method until the user types "stop".
o Print the list, its length, and the sum of numeric elements (if any).
my_list = []
while True:
if item.lower() == 'stop':
break
my_list.append(item)
sum =0
for x in my_list:
2. List Sorting
Write a Python program that:
a. Prompts the user to enter items into a list until they type "stop".
b. Creates two new lists: one sorted in ascending order and the other in descending
order.
c. Displays both sorted lists.
my_list = []
while True:
if item.lower() == 'stop':
break
``
my_list.append(item)
sorted_asc = sorted(my_list)
items = line.split(";")
print(item)
4. Write python code that find all pairs that add up to a target sum.
def find_pairs(lst, target):
pairs = []
for i in range(len(lst)):
pairs.append((lst[i], lst[j]))
return pairs
numbers = [2, 4, 3, 5, 7, 8]
target_sum = 10
print(find_pairs(numbers, target_sum))
``
5. Write python code that rotate a list by n positions.
def rotate_list(lst, n):
print(is_palindrome([1, 2, 3, 2, 1]))
new_list = []
for x in numbers:
if x not in new_list:
new_list.append(x)
print(new_list)
8. Write python code that replace all even numbers in a list with 0.
numbers = [2, 4, 3, 5, 3, 8, 5, 10 , 9,12]
i=0
for x in numbers:
if x %2 == 0:
numbers[i] =0
i+=1
print(numbers)
``
9.Write a python program that uses a list to store student marks and calculates their sum, maximum,
minimum, and average.
Input:
85
90
78
92
88
ANSWER:
marks = []
for i in range(n):
marks.append(mark)
# Initialize variables
total = 0
maximum = marks[0]
minimum = marks[0]
``
# Calculate sum, max, and min
# Calculate average
average = total / n
print(f"Marks: {marks}")
``