Skip to main content

files in Python

 Files

1. Read file

    # Use open function to read the content of a file!
    # f = open('sample.txt', 'r')
    f = open('sample.txt'# by default the mode is r
    # data = f.read()
    data = f.read(5# reads first 5 characters from the file
    print(data)
    f.close()

O/P: avi

2. Readline 

    f = open('sample.txt')
    # read first line
    data = f.readline() 
    print(data)

    # Read second line
    data = f.readline() 
    print(data)

    # Read third line
    data = f.readline() 
    print(data)

    # Read fourth line... and so on...
    data = f.readline() 
    print(data)
    f.close()

O/P: ok i have done


what u required


i am done wiht y


ok what aare you doing


3. write

    f = open("copy.txt"'w')  #Write from start del privious all data
    f.write("plese help to me")
    f.close()

    f= open('copy.txt''a')  #add string at end 
    f.write("im waitning")
    f.close()

O/P: wihat was that im waitning im waitning

4. with open as f

    with  open('copy.txt''r'as f:  #close atomatic with fuction
        a= f.read()
    with open('copy.txt''w'as f:
        a= f.write("ok i have done")
    print(a)

O/P: 14

5. string present or not

    f = open('poems.txt')
    t = f.read()
    if 'twinkle' in t:
        print("Twinkle is present")
    else:
        print("Twinkle is not present")
    f.close()

O/P: Twinkle is present

6. high score store if not present in file

    def game():
        return 44675

    score = game()
    with open("hiscore.txt"as f:
        hiScoreStr = f.read()
        
    if hiScoreStr=='':
        with open("hiscore.txt""w"as f:
            f.write(str(score))

    elif int(hiScoreStr)<score :
        with open("hiscore.txt""w"as f:
            f.write(str(score))

O/P: 44675

7. create multipal file of tables


for i in range(221):
    with open(f"tables/Multiplication_table_of_{i}.txt"'w'as f:
        for j in range(111):
            f.write(f"{i}X{j}={i*j}")
            if j!=10:
                f.write('\n')

O/P: created file of table up to 20

8. replace specific word

    with open('sample1.txt'as f:
        content= f.read()

    content= content.replace('avi'"ytgjuuy")

    with open('sample1.txt''w'as f:
        f.write(content)

O/P:

9.  Replace multipal word by one word

    words = ["donkey""kaddu""mote"]

    with open("sample.txt"as f:
        content = f.read()


    for word in words:
        content = content.replace(word"$%^@$^#")
        with open("sample.txt""w"as f:
            f.write(content)

O/P:

10. check string present or not in file

    with open("log.txt"as f:
        content = f.read()

    if 'python' in content.lower():
        print("Yes python is present")
    else:
        print("No python is not present")

O/P: yes python is present

11. print line number on which python is present

content = True
i = 1
with open("log.txt"as f:
    while content:
        content = f.readline()
        if 'python' in content.lower():
            print(content)
            print(f"Yes python is present on line number {i}"
        i+=1

O/P: Yes python is present on line number 39

12.  copy from one file to another

with open("this.txt"as f:
    content = f.read()

with open("copy.txt"'w'as f:
    f.write(content)

O/P:

13. find if file are same or not

file1 = "log.txt"
file2 = "this.txt"

with open(file1as f:
    f1 = f.read()

with open(file2as f:
    f2= f.read()

if f1 == f2:
    print("Files are identical")
else:
    print("Files are not identical")

O/P: files are not identical

14. file to make empty

filename = "sample.txt"
with open(filename"w"as f:
    f.write("")

O/P:

15. rename file

import os

oldname = "sample2.txt"
newname = "renamed_by_python.txt"
with open(oldnameas f:
    content = f.read()

with open(newname"w"as f:
    f.write(content)

os.remove(oldname)

O/P:

16.

O/P:

1.

O/P:

1.

O/P:

1.

O/P:

1.O/P:

1.O/P:

1.O/P:

1.O/P:

1.O/P:

1.O/P:

1.O/P:

1.O/P:

1.O/P:

1.O/P:

1.O/P:

1.O/P:

1.O/P:

1.O/P:

1.O/P:

1.O/P:

1.O/P:

1.O/P:

1.

Popular posts from this blog

deploying Machine learning Model : pkl, Flask,postman

1)Create model and train          #  importing Librarys         import pandas as pd         import numpy as np         import matplotlib . pyplot as plt         import seaborn as sns         import requests         from pickle import dump , load         # Load Dataset         url = "http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"         names = [ "sepal_length" , "sepal_width" , "petal_length" , "petal_width" , "species" ]         # Loading Dataset         df = pd . read_csv ( url , names = names )         df . tail ( 11 )         df . columns         test = [         { 'sepal_length' : 5.1 , 'sepal_width' : 3.5 , 'peta...

Binomial Distribution

  The binomial distribution formula is:                                                    b(x; n, P) =  n C x  * P x  * (1 – P) n – x Where: b = binomial probability x = total number of “successes” (pass or fail, heads or tails etc.) P = probability of a success on an individual trial n = number of trials Note:  The binomial distribution formula can also be written in a slightly different way, because  n C x  = n! / x!(n – x)! (this binomial distribution formula uses factorials  (What is a factorial? ). “q” in this formula is just the probability of failure (subtract your probability of success from 1). Using the First Binomial Distribution Formula The binomial distribution formula can calculate the probability of success for binomial distributions. Often you’ll be told to “plug in” the numbers to the  formul...

Tabel of content in Jupyter notebook

  SourceForge uses markdown syntax everywhere to allow you to create rich text markup, and extends markdown in several ways to allow for quick linking to other artifacts in your project. Markdown was created to be easy to read, easy to write, and still readable in plain text format. Links Reference Links Artifact Links User Mentions Basic Text Formatting Blockquotes Preformatted Text Lists Tables Headers Horizontal Rules Images Videos Escapes and HTML More Headers Table of Contents Code Highlighting Includes Neighborhood Notifications Project Info Macros Thanks Links Most URLs will automatically be turned into links. To be explicit, just write it like this: <http://someurl> <somebbob@example.com> Output: http://someurl somebbob@example.com To use text for the link, write it: [like this](http://someurl) Output: like this You can add a *title* (which shows up under the cursor): [like this](http://someurl "this title shows up when you hover") Output: like this Refe...