From dda8b8af51b3347e300d27750926f80e8a0c46a8 Mon Sep 17 00:00:00 2001 From: Chand Date: Mon, 16 Oct 2023 12:05:46 +0530 Subject: [PATCH] File Handling Example Added --- .../File Handling/File Handling.py | 53 +++++++++++++++++++ Python Projects/File Handling/marks.txt | 17 ++++++ Python Projects/File Handling/names.txt | 14 +++++ 3 files changed, 84 insertions(+) create mode 100644 Python Projects/File Handling/File Handling.py create mode 100644 Python Projects/File Handling/marks.txt create mode 100644 Python Projects/File Handling/names.txt diff --git a/Python Projects/File Handling/File Handling.py b/Python Projects/File Handling/File Handling.py new file mode 100644 index 0000000..1f05558 --- /dev/null +++ b/Python Projects/File Handling/File Handling.py @@ -0,0 +1,53 @@ +""" + An example program to showcase how we can read/write from/to files in python + + Objective: + - We have an list of names. Write the names to names.txt file. + - Read the names from names.txt file and now write it to marks.txt file(each person got some marks in exam) + + Steps: Read and Write operation + - Open a file + - Do some opertations(Read from it) + - Write to another file + - Close the files + + + Contributor: Anirban Chand +""" + +from random import randint + +# Open a file in write mode +in_file = open('names.txt', 'w') + +# do something +names = ['Levi', 'Eren', 'Mikasa', 'Hange', 'Erwin', 'Armin', 'Grisha', 'Historia', 'Dina', 'Jean', 'Sasha', 'Hitch', 'Hannes', 'Marlo'] +for name in names: + in_file.write(name) + in_file.write('\n') + +in_file.close() + + +# Open a file +in_file = open('names.txt', 'r') +out_file = open('marks.txt', 'w') + +# Write the headings +out_file.write('Names') +out_file.write('\t\t \t\t') +out_file.write('Marks\n') +out_file.write('_____') +out_file.write('\t\t \t\t') +out_file.write('_____\n\n') + +# Write names their marks in marks.txt file +for name in in_file: + marks = randint(30, 100) + name = name[:-1] + out_file.write(name) + out_file.write('\t\t- \t\t') + out_file.write(str(marks)+'\n') + +in_file.close() +out_file.close() \ No newline at end of file diff --git a/Python Projects/File Handling/marks.txt b/Python Projects/File Handling/marks.txt new file mode 100644 index 0000000..ccb43db --- /dev/null +++ b/Python Projects/File Handling/marks.txt @@ -0,0 +1,17 @@ +Names Marks +_____ _____ + +Levi - 80 +Eren - 37 +Mikasa - 90 +Hange - 93 +Erwin - 42 +Armin - 72 +Grisha - 59 +Historia - 51 +Dina - 39 +Jean - 68 +Sasha - 59 +Hitch - 80 +Hannes - 58 +Marlo - 31 diff --git a/Python Projects/File Handling/names.txt b/Python Projects/File Handling/names.txt new file mode 100644 index 0000000..a7394d6 --- /dev/null +++ b/Python Projects/File Handling/names.txt @@ -0,0 +1,14 @@ +Levi +Eren +Mikasa +Hange +Erwin +Armin +Grisha +Historia +Dina +Jean +Sasha +Hitch +Hannes +Marlo