<jupyter_start><jupyter_text>File Handling  What Is a File?A file is a contiguous set of bytes used to store data. This data is organized in a specific format and can be anything as simple as a text file or as complicated as a program executable.Files on most modern file systems are composed of three main parts:**Header:** metadata about the contents of the file (file name, size, type, and so on).**Data:** contents of the file as written by the creator or editor.**End of file (EOF):** special character that indicates the end of the file.  File PathsWhen you access a file on an operating system, a file path is required. The file path is a string that represents the location of a file. It’s broken up into three major parts:**Folder Path:** the file folder location on the file system where subsequent folders are separated by a forward slash / (Unix) or backslash \ (Windows).**File Name:** the actual name of the file.**Extension:** the end of the file path pre-pended with a period (.) used to indicate the file type     Here’s a quick example. Let’s say you have a file located within a file structure like this:        /      │    ├── path/  ← Your current working directory (cwd) is here    |   │    |   ├── to/      |   │   └── cats.gif  ← Accessing this file    |   │    |   └── dog_breeds.txt    |    └── animals.csv Let’s say you wanted to access the cats.gif file.The Folder Path is path/to/. The File Name is cats. The File Extension is .gif. So the full path is path/to/cats.gif.  Relative or Absolute Path?A path is either **relative** or **absolute**. An **absolute path** always contains the **root element and the complete directory** list required to locate the file. **For example, /home/sally/statusReport is an absolute path.** All of the information needed to locate the file is contained in the path string.A **relative path** needs to be combined with another path in order to access a file. **For example, joe/foo is a relative path.** Without more information, a program cannot reliably locate the joe/foo directory in the file system. **Relative path**%load aa/a.py %load ../bb/a.py **Absolute Path**%load/home/HaseebRajput/WindowData/Course/ISLAMABAD/12:30_to_03:30/class9(File_Handling)/a.py  Opening and Closing a File in Python When you want to work with a file, the first thing to do is to open it. This is done by invoking the open() built-in function. open() has a single required argument that is the path to the file. open() has a single return, the file object<jupyter_code>file = open('dog_breeds.txt')
file
list(file)
open('abc.txt')
list(open('abc.txt'))<jupyter_output><empty_output><jupyter_text>After you open a file, the next thing to learn is how to close it.**Warning:** You should always make sure that an open file is properly closed. **The first way to close a file**<jupyter_code>data = open('dog_breeds.txt')

for r in data:
    print(r)

data.close()<jupyter_output>Pug\r\n

<NAME> Terrier\r\n

English Springer Spaniel\r\n

German Shepherd\r\n

Staffordshire Bull Terrier\r\n

Cavalier King Charles Spaniel\r\n

Golden Retriever\r\n

West Highland White Terrier\r\n

Boxer\r\n

Border Terrier\r\n<jupyter_text>**The second way to close a file is to use the try-finally block:**<jupyter_code>reader = open('dog_breeds.txt')
try:
    # Further file processing goes here
    for r in reader:
        print(r)
finally:
    reader.close()<jupyter_output>Pug\r\n

<NAME> Terrier\r\n

English Springer Spaniel\r\n

German Shepherd\r\n

Staffordshire Bull Terrier\r\n

Cavalier King Charles Spaniel\r\n

Golden Retriever\r\n

West Highland White Terrier\r\n

Boxer\r\n

Border Terrier\r\n<jupyter_text>**The Third way to close a file is to use the with statement:**    The with statement automatically takes care of closing the file once it leaves the with block, even in cases of error. I highly recommend that you use the with statement as much as possible, as it allows for cleaner code and makes handling any unexpected errors easier for you.<jupyter_code>with open('dog_breeds.txt') as reader:
    # Further file processing goes here
    for r in reader:
        print(r)<jupyter_output>Pug\r\n

<NAME> Terrier\r\n

English Springer Spaniel\r\n

German Shepherd\r\n

Staffordshire Bull Terrier\r\n

Cavalier King Charles Spaniel\r\n

Golden Retriever\r\n

West Highland White Terrier\r\n

Boxer\r\n

Border Terrier\r\n<jupyter_text>Modes Options    Most likely, you’ll also want to use the second positional argument, mode. This argument is a string that contains multiple characters to represent how you want to open the file. The default and most common is 'r', which represents opening the file in read-only mode as a text file:                      | r   r+   w   w+   a   a+    ------------------|--------------------------    read              | +   +        +        +    write             |     +    +   +    +   +    write after seek  |     +    +   +    create            |          +   +    +   +    truncate          |               position at start | +   +    +   +    position at end   |                   +<jupyter_code>with open('dog_breeds.txt', 'r') as reader:
    # Further file processing goes here
    for r in reader:
        print(r)<jupyter_output>Pug\r\n

<NAME> Terrier\r\n

English Springer Spaniel\r\n

German Shepherd\r\n

Staffordshire Bull Terrier\r\n

Cavalier King Charles Spaniel\r\n

Golden Retriever\r\n

West Highland White Terrier\r\n

Boxer\r\n

Border Terrier\r\n<jupyter_text>Categories of file objects:Text filesBuffered binary filesRaw binary files  Text File TypesA text file is the most common file that you’ll encounter. Here are some examples of how these files are opened:<jupyter_code>open('abc.txt')
open('abc.txt', 'r')
open('abc.txt', 'w')<jupyter_output><empty_output><jupyter_text>file = open('dog_breeds.txt')type(file)<jupyter_code>#### Buffered Binary File Types
A buffered binary file type is used for reading and writing binary files. Here are some examples of how these files are opened:<jupyter_output><empty_output><jupyter_text>open('abc.txt', 'rb')open('abc.txt', 'wb')<jupyter_code>With these types of files, open() will return either a BufferedReader or BufferedWriter file object:<jupyter_output><empty_output><jupyter_text>file = open('dog_breeds.txt', 'wb')type(file) file = open('dog_breeds.txt', 'rb')type(file)<jupyter_code>#### Raw File Types
A raw file type is:

“generally used as a low-level building-block for binary and text streams.” (Source)

It is therefore not typically used.

Here’s an example of how these files are opened:<jupyter_output><empty_output><jupyter_text>open('abc.txt', 'rb', buffering=0)<jupyter_code>file = open('dog_breeds.txt', 'rb', buffering=0)
type(file)<jupyter_output><empty_output><jupyter_text>Reading and Writing Opened FilesOnce you’ve opened up a file, you’ll want to read or write to the file. First off, let’s cover reading a file. There are multiple methods that can be called on a file object to help you out:MethodWhat It Does.read(size=-1)This reads from the file based on the number of size bytes. If no argument is passed or None or -1 is passed, then the entire file is read..readline(size=-1)This reads at most size number of characters from the line. This continues to the end of the line and then wraps back around. If no argument is passed or None or -1 is passed, then the entire line (or rest of the line) is read..readlines()This reads the remaining lines from the file object and returns them as a list.<jupyter_code>with open('dog_breeds.txt', 'r') as reader:
    # Read & print the entire file
    print(reader.read())
with open('dog_breeds.txt', 'r') as reader:
    # Read & print the first 5 characters of the line 5 times
    print(reader.readline(5))
    # Notice that line is greater than the 5 chars and continues
    # down the line, reading 5 chars each time until the end of the
    # line and then "wraps" around
    print(reader.readline(5))
    print(reader.readline(5))
    print(reader.readline(5))
    print(reader.readline(5))
f = open('dog_breeds.txt')
f.readlines()  # Returns a list object

f = open('dog_breeds.txt')
list(f)
#with open(file) as <variable>:
with open('abc.txt', mode='r') as f:
    content = f.read()
    print(type(content))
    print(content)
#with open(file) as <variable>:
with open('abc.txt', mode='r') as f:
    content = f.readline()
    print(type(content))
    print(content)<jupyter_output><class 'str'>
Hello world<jupyter_text>Iterating Over Each Line in the FileA common thing to do while reading a file is to iterate over each line. Here’s an example of how to use the Python .readline() method to perform that iteration:<jupyter_code>with open('dog_breeds.txt', 'r') as reader:
    # Read and print the entire file line by line
    line = reader.readline()
    while line != '':  # The EOF char is an empty string
        print(line, end='')
        line = reader.readline()<jupyter_output>Pug
<NAME>
English Springer Spaniel
<NAME>
Staffordshire Bull Terrier
Cavalier King <NAME>
Golden Retriever
West Highland White Terrier
Boxer
Border Terrier<jupyter_text>Another way you could iterate over each line in the file is to use the Python .readlines() method of the file object. Remember, .readlines() returns a list where each element in the list represents a line in the file:<jupyter_code>with open('dog_breeds.txt', 'r') as reader:
    for line in reader.readlines():
        print(line, end='')<jupyter_output>Pug
<NAME>
English Springer Spaniel
Ger<NAME>pherd
Staffordshire Bull Terrier
Cavalier King <NAME>
Golden Retriever
West Highland White Terrier
Boxer
Border Terrier<jupyter_text>However, the above examples can be further simplified by iterating over the file object itself:<jupyter_code>with open('dog_breeds.txt', 'r') as reader:
    # Read and print the entire file line by line
    for line in reader:
        print(line, end='')<jupyter_output>Pug
<NAME>
English Springer Spaniel
<NAME>
Staffordshire Bull Terrier
Cavalier King <NAME>
Golden Retriever
West Highland White Terrier
Boxer
Border Terrier<jupyter_text>**Note:** Some of the above examples contain print('some text', end=''). The end='' is to prevent Python from adding an additional newline to the text that is being printed and only print what is being read from the file.  Now let’s dive into writing files. MethodWhat It Does.write(string)This writes the string to the file..writelines(seq)This writes the sequence to the file. No line endings are appended to each sequence item. It’s up to you to add the appropriate line ending(s).<jupyter_code>with open('dog_breeds.txt', 'r') as reader:
    # Note: readlines doesn't trim the line endings
    dog_breeds = reader.readlines()

with open('dog_breeds_reversed.txt', 'w') as writer:
    # Alternatively you could use
    # writer.writelines(reversed(dog_breeds))

    # Write the dog breeds to the file in reversed order
    for breed in reversed(dog_breeds):
        writer.write(breed)
#with open(file) as <variable>:
with open('abc.txt', mode='r') as f:
    f.write("Pakistan zinda bad!") # error generate bcz of file mode...
with open('abc1.txt', mode='w') as f:
    f.write("Pakistan zinda bad \n We are pakistani!")
with open('abc1.txt', mode='r') as f:
    print(f.read())
with open('abc1.txt', mode='w') as f:
    f.write("Hello World")
with open('abc1.txt', mode='r') as f:
    print(f.read())
with open('abc2.txt', 'a') as f:
    f.write("Haseeb\n")
with open('abc2.txt', mode='r') as f:
    print(f.read())
with open('abc3.txt', 'a+') as f:
    f.write("Adan")
    print(f.readlines())
with open('abc3.txt', 'a+') as f:
    f.write("Rauf")
    f.seek(0)
    print(f.readlines())
with open('abc4.txt', 'r+') as f:
    a = list(reversed(f.readlines()))
    b = list(reversed(['A',"B",'C']))
    c = b + a
    d = "".join(c)
    f.seek(0)
    f.write(d)
    print(d)
with open('abc4.txt', mode='r') as f:
    print(f.read())<jupyter_output>CBA1
CBA32
{'fraction_non_alphanumeric': 0.1054396110971419, 'fraction_numerical': 0.003268795574553684, 'mean_word_length': 3.8268608414239482, 'pattern_counts': {'":': 0, '<': 69, '<?xml version=': 0, '>': 69, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '15', 'dir': 'jupyter-structured-clean-dedup', 'id': '148453', 'license': 'MIT', 'n_tokens_mistral': 3778, 'n_tokens_neox': 3711, 'n_words': 1485, 'path': 'Day_14(Python_File_Handling)/Day_14(Python_File_Handling).ipynb', 'repo_name': 'HaseebRajput007/100DaysOfCode-DataScience', 'size': '12043'}