Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
38 views6 pages

File Handling 2

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

File Handling 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 6
Computer Seionce with Python GD ret For example: nen('C:\ \Python\ \Name txt", f= open C-\NPyth ne ' Modo (writo modo) Fie object Frio path File Namo eC e directory, sub-directory and fere, you can notice that the directory, . heer separated using two back sla hes (\\). Since, Note 2 te ray ingle slash has a special meaning (ic, escape | TR U8 of prof. + mates | sequence) in its use, so two back slashes (\\) are uused in| the string raw sting wich | acai | indicates that thore i ame of the file. snvéen the path name of the meaning of using backlash | However, you can use character ras prefix to the path |_character in the string name, if you want to use single slash (\) explicitly as aa J directories and file separator, the above syntax can be written as: £ = open(r “C:\Python\Name.txt","w") ca ‘ Profix r Single use of backward slash Components of a Path To understand various components of a path name, let us take an example: Suppose, a data file Name.txt has been created using the file path as: C:\Users\ClassXII\Name.txt The different components can be described as shown belo C:\Users\ClassXII\Name.docx 2 tw 1 Root Folder — File Name Parent Current Folder Folder Where, + Root folder: It is created at the time of partitioning the @ hard disk during system installation. C: drive is considered Note celosed ) e For example: © openCName.t',w") Noto Sy ° | Python clesoe a fe automata | whom tho fo object a vr cano? | * An operation performed an a closed file * Yous form task(a) to opon another fie. But, iis goad practice to use close ) function felosal) aftor complotion of the task. A text file in Python has many attributes, Some of the file attributes are as listed below: fname - zi 2 Lmode Returns access mode with which file was opened. 3. Lelosed, Returns True if file is closed, otherwise False. } Fsanppte be A-eade snippet is written as: f= open(’Name.nt’, "w") print("Name of the file: ", fname) print(’Opening, mode of the file: ",Lmode) print("File closed or Not: ", felosed) When you type the output as shown below: n statements on the Python interactive mode, it will produce fe open(’Name.tnt’, "w") print(’Name of the file: ", (name) Name of the file: Name.tst print(Opening mode of the file: ",Lmode) Opening mode of the file: w print(Tile closed or Not: ", closed) File closed or Not: False Fvample & A code snippet is written as fe open("C:\\Python33\ \Name.tt’, “") print(’Name and path of the file: ", (name) print(’Opening, mode of the file: ", Emode) print("Tile closed or Not: °, f.closed) When you type the given statements on the Python interactive mode, it will produce the output as shown below: Captor =e any EDD (sos & open(’C:\\Pythond3\ \Namest ) o> print(’Name and path of the file: ", fname) Name and path of the file: C\Python’d\Namie.tst som print("Opening mode of the file: “yimode) pening mode of the files r print('File closed or Not Jose or Not: False: ' fclosed) Q. Note 5 " ynen path name of a flo is displayod, tho foldor, suboldor and fle appoar on tho sereon woparatod by | single slash (\) only, irrespective of tho mattar whothor thoy aro used with singlo or double slash in tho. code. ng data in a text file W Writing data refers to as storing data or information in a file. Trorder to write data, the fle must be opened in *w" Noto 9. mode. In case, a file is already created and you try to 1e- open it in "Ww" mode, the previous contents will be deleted and you will be provided a fresh file for writing data into it, Jin a tonto, at tho data | including numaric values aro | storod as stings The following steps must be taken while writing data inte a file: + Open the file in" + Define the file name along with the extension, «Set the path for reaching to the file (optional). mode with the help of a file object that serves as a link to the file, Python uses the following two methods for writing data into a text file: (a) write() The method accepts the data as string to store it in the text file, Syntax: For example: fw= open(’Name.tat’,"w") fw.write("Abhiraj Kumar’) Program tuo fwavrite(’Manas Shahi) rite(’Sohan Mishra") fwavrite(“Anmol Kishore") fw.write("Nishi Kant") fw.close( ) fw The above prog de written to the text file ‘e program code written to open the te Note .@, 2 (Name.txt) must be saved in another file (say, Sample) inne Sam } Which is a program file saved in Python platform. red CLs Cea tel data written into the filo in a Thus, the above code will create a text file (Name.txt) in single run of welta( ) function, the current directory, if it does not exist. In case, the file ©\sts then it will overwrite the content. you run the above code, nothing will be displayed because the names are only to be Stored in the file. You can view the data file (icon) on the current directly (Say, desktop), ED W001 ot Comte Besenen wat Pron You ean also open the text file in Notepad - ae 3 and view its contents. It is shown as Brame Norepad Fe (AN Foemat View Help [Abnira) KumarManes ShahiSohan MishraAnmol KishoreNishi Kant Here, you will notice that all the data are written continuously in a single line in the tex file. It is because of the fact that the write( ) doesn't add a new line character (\n) on its ‘own. If you want to display each of the names in a new line then you must include the newline character explicitly while writing data into the file. The above code can be modified using (\n) character as shown belo’ fwe= open("Name.txt’,"w") fwavrite("Abhiraj Kumar\n") note 2 fw.write("Manas Shahi\n") "The data or information stored fw.write("Sohan Mishra\n") in one execution of write( ) fwawrite("Anmol Kishore\n") function ‘wil be.a site record of the file fw.write("Nishi Kant") fw.close( ) Now, when you open the text file in Notepad, it will display the names in the diff lines as shown below: Name - Notepad - Oo x File Edit Format View Help \Abhiraj Kumar Manas Shahi Sohan Mishra ‘Anmol Kishore Nishi Kant < Ln 1, Colt 100% __ Windows (CRLF) UTF-8 The above code to write data into a text file can also be developed by using a loop. It is illustrated as: fw= open("Name.txt’,"w") for a in rang nm=input("Enter name:") f fwv.close( ) -write(nm +'\n') Chapter 6= hin tanding EDD eats tn tte E jw FTpanen sete - : a - [ae cae ten Cai, Yt ay RARER C CCA CRT TT DA WE VTE Le Cnt Pw 3 + TOOHPELANES, MOEMILAT GE “Hioenae ty? fs sore bnformat aenenenne RESTART) CAUREALDLT ER STRESS ann wt Ch Roe nea Rant (REE n ant Romar eet Sheen ENANE AEE, RS aya Kumar ey\Deadt op); apy = t Se Be ine you open the text tile in Notepad, it will display the s shown below whe pred data of the file in Dame Notepad He LE Fount Vw Hel Aman Kishore Komal Kant Nishant Kumar ‘Vimal Shahi |Suit Dayal WAG 00% Windows (CRI UT ») writelines() tunetion is used to store che items as a list of strings in the file. Syntar:

You might also like