|
| 1 | +"""File I/O python |
| 2 | +python can be used to perform operation on a file (read and write) |
| 3 | +Type of all files |
| 4 | +1. text files: .txt, .docx, .log etc .(stored in char form) |
| 5 | +2. binary files: .mp4, .mov ,.png , .jpeg etc.(0,1) |
| 6 | +
|
| 7 | +# 1 & 2 are at the end bytes |
| 8 | +#ROM{random access memory}= fast excution, valatile(data will be deleted) OR files can be used. |
| 9 | +
|
| 10 | +#open , read ,close file |
| 11 | +we we have to open the file before read and write |
| 12 | +EX: |
| 13 | + #function |
| 14 | +f = open("file.name",mode) |
| 15 | + #sample.txt #r: read mode |
| 16 | + #demo.docx #w: write mode |
| 17 | +""" |
| 18 | +#read method |
| 19 | + |
| 20 | +f = open("para.txt","r") |
| 21 | + |
| 22 | +data = f.read() #reads entire file |
| 23 | +data1 = f.read(2) #reads word by word |
| 24 | +data2 = f.readline(2) #reads one line at a time |
| 25 | + |
| 26 | +print(data) |
| 27 | +print(data1) |
| 28 | +print(data2) |
| 29 | + |
| 30 | + |
| 31 | +# write method |
| 32 | + |
| 33 | +f = open("para.txt","w") |
| 34 | +h = open("para.txt","a") |
| 35 | + |
| 36 | +data = f.write("then i will move to html css javascript") |
| 37 | + |
| 38 | +f.close() |
| 39 | +h.close() |
| 40 | + |
| 41 | +#opration |
| 42 | +f = open("para.txt","r+") |
| 43 | +#r+ reading and writing note pointer at start - no truncate |
| 44 | +#w+ writhing and reading note - truncate |
| 45 | +#a+ open the file note pointer placed at end |
| 46 | + |
| 47 | +"""" |
| 48 | +#character meaning |
| 49 | +'r' open for reading (default) |
| 50 | +'w' open for writing, truncating the file first |
| 51 | +'x' create a new file and open it for writing |
| 52 | +'a' open for writing, appending to the end of the file if it exists |
| 53 | +'b' binary mode |
| 54 | +'t' text mode (default) |
| 55 | +'+' open a disk file for updating (reading and writing)""" |
| 56 | + |
| 57 | + |
| 58 | +#with syntax |
| 59 | + #giving diff name |
| 60 | +with open("para.txt","r") as j: |
| 61 | + data= j.read() |
| 62 | + print(j) |
| 63 | + |
| 64 | +with open("para.txt","w") as j: |
| 65 | + j.read("new data") |
| 66 | + |
| 67 | +"""deleting a file method |
| 68 | +using os module |
| 69 | +module (like a code library) is a filr written by another programmer that generally has a |
| 70 | +function we can use .""" |
| 71 | + |
| 72 | +#EX |
| 73 | +import os |
| 74 | + |
| 75 | +#os.remove("para.txt") |
| 76 | + |
| 77 | + |
| 78 | + |
0 commit comments