Python Program to Read a Random Line from a File

Python Program to Read a Random Line from a File

Files in Python:

One of the most important subjects for programmers and automation testers is Python file handling (also known as File I/O). It is necessary to work with files in order to write to or read data from them.

Also, if you didn’t know, I/O operations are the most expensive processes where a programme can go wrong. As a result, you must use extreme caution while implementing file processing for reporting or any other reason. Optimizing a single file action can help in the creation of a high-performing application or a reliable automated software testing solution.

Consider the following scenario: you’re planning to construct a large Python project with a large number of workflows. Then it’s unavoidable that you don’t make a log file. You’ll also be handling the log file’s read and write activities. Debugging huge applications with log files is a terrific way to go. It’s usually better to consider a scalable design from the start, as you won’t be sorry later if you didn’t.

Given a file, the task is to read a random line from the given File in Python

Program to Read a Random Line from a File in Python

Below is the full approach for reading a random line from the given File in Python

Approach:

  • Import random module using the import keyword
  • Make a single variable to store the path of the file. This is a constant value. This value must be replaced with the file path from your own system in the example below.
  • Open the file in read-only mode. In this case, we’re simply reading the contents of the file.
  • Get all the lines of the file using the read(), splitlines() functions and store it in a variable.
  • Print a random line from the given file using the random.choice() function by passing the above lines as an argument to it.
  • The Exit of Program.

Below is the implementation:

# Import random module using the import keyword
import random
# Make a single variable to store the path of the file. This is a constant value.
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Open the file in read-only mode. In this case, we're simply reading the contents of the file.
with open(givenFilename, 'r') as givenfilecontent:
    # Get all the lines of the file using the read(), splitlines() functions and 
    # Store it in a variable
    file_lines = givenfilecontent.read().splitlines()
    # Print a random line from the given file using the random.choice() function
    # by passing the above lines as an argument to it
    print(random.choice(file_lines))

Output:

btechgeeks

File Content:

hello
thisis 
btechgeeks
welcomeall

Explanation:

  • The file path is stored in the variable ‘file name.’ Change the value of this variable to the path of your own file.
  • Dragging and dropping a file onto the terminal will show its path. The code will not run unless you change the value of this variable.
  • The file will be opened in reading mode. Use the open() function to open a file. The path to the file is the method’s first parameter, and the mode to open the file is the method’s second parameter.
  • When we open the file, we use the character ‘r’ to signify read-mode.
  • We use random.choice() method to select random line from list of lines.

Google Colab Images:

Files and Code:

Python Program for Reading Last N Lines of a File

Python Program for Reading Last N Lines of a File

Files in Python:

Python file handling is a way of saving program output to a file or reading data from a file. File handling is a crucial concept in the programming world. File management is used in almost every form of project. Assume you are constructing an inventory management system. You have data in the inventory management system related to sales and purchases, thus you must save that data somewhere. Using Python’s file management, you can save that data to a file. You must be given data in the form of a comma-separated file or a Microsoft Excel file if you wish to conduct data analysis. Using file handling, you can read data from a file and write output back into it.

Give the N value and file the task is to read the last n lines of the file in Python.

Program for Reading Last N Lines of a File in Python

Method #1: Using For loop (Static Input)

The concept behind this technique is to utilize a negative iterator with the readlines() function to read all of the lines requested by the user from the end of the file.

Approach:

  • Make a single variable to store the path of the file. This is a constant value. This value must be replaced with the file path from your own system in the example below.
  • Give the n value as static input and store it in a variable.
  • Open the file in read-only mode. In this case, we’re simply reading the contents of the file.
  • Get all the lines of the file using the readlines() function and store it in a variable.
  • Iterate in the above lines list using the for loop to get the last n lines of a file using the negative indexing.
  • Print the last n lines of a given file.
  • The Exit of Program.

Below is the implementation:

# Make a single variable to store the path of the file. This is a constant value.
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Give the n value static input and store it in a variable.
gvn_n_val = 2
# Open the file in read-only mode. In this case, we're simply reading the contents of the file.
with open(givenFilename, 'r') as givenfilecontent: 
    # Get the lines of the file using the readlines() function
    lines_lst= givenfilecontent.readlines()
    print("The last",gvn_n_val,"lines of a given file are:")
    # Iterate in the above lines list using the for loop to get the last
    # n lines of a file using the negative indexing.
    for fline in (lines_lst[-gvn_n_val:]):
        # Print the last n lines of a given file.
        print(fline, end ='')
 
 

Output:

The last 2 lines of a given file are: 
BTech Geeks have listed a wide collection 
of Python Programming Examples.

Method #2: Using For loop (User Input)

Approach:

  • Make a single variable to store the path of the file. This is a constant value. This value must be replaced with the file path from your own system in the example below.
  • Give the n value as user input using the int(input()) function and store it in a variable.
  • Open the file in read-only mode. In this case, we’re simply reading the contents of the file.
  • Get all the lines of the file using the readlines() function and store it in a variable.
  • Iterate in the above lines list using the for loop to get the last n lines of a file using the negative indexing.
  • Print the last n lines of a given file.
  • The Exit of Program.

Below is the implementation:

# Make a single variable to store the path of the file. This is a constant value.
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Give the n value user input using the int(input()) function and store it in a variable.
gvn_n_val = int(input("Enter some random number = "))
# Open the file in read-only mode. In this case, we're simply reading the contents of the file.
with open(givenFilename, 'r') as givenfilecontent: 
    # Get all the lines of the file using the readlines() function
    lines_lst= givenfilecontent.readlines()
    print("The last",gvn_n_val,"lines of a given file are:")
    # Iterate in the above lines list using the for loop to get the last
    # n lines of a file using the negative indexing.
    for fline in (lines_lst[-gvn_n_val:]):
        # Print the last n lines of a given file.
        print(fline, end ='')
 
 

Output:

Enter some random number = 3 
The last 3 lines of a given file are: 
The best way to learn the language is by practicing. 
BTech Geeks have listed a wide collection 
of Python Programming Examples.

File Content:

hello this is btechgeeks
welcome to btechgeeks
Good morning this is btechgeeks 
By now you might be aware that Python is a Popular Programming Language 
used right from web developers to data scientists. Wondering what exactly Python looks like and how it works? 
The best way to learn the language is by practicing. 
BTech Geeks have listed a wide collection
of Python Programming Examples.

Google Colab Images:

Files and Code:

Python Program to Write a List Content to a File

Python Program to Write a List Content to a File

Files in Python:

Python file handling is a way of saving program output to a file or reading data from a file. File handling is a crucial concept in the programming world. File management is used in almost every form of project. Assume you are constructing an inventory management system. You have data in the inventory management system related to sales and purchases, thus you must save that data somewhere. Using Python’s file management, you can save that data to a file. You must be given data in the form of a comma-separated file or a Microsoft Excel file if you wish to conduct data analysis. Using file handling, you can read data from a file and write output back into it.

Given a file, the task is to write a list content into the given File.

Program to Write a List Content to a File in Python

Below is the full approach for writing a list content into the given File.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Make a single variable to store the path of the file. This is a constant value. This value must be replaced with the file path from your own system in the example below.
  • Open the file in write mode. In this case, we’re writing the contents into the file.
  • Iterate in the above-given list using the for loop.
  • Write the iterator value(list elements) into the file using the write() function.
  • Open the file in read-only mode. In this case, we’re simply reading the contents of the file.
  • Read the above file using the read() function(get the content) and print it.
  • The Exit of Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ['hello', 'this', 'is', 'Btechgeeks', 'good morning']
# Make a single variable to store the path of the file. This is a constant value. 
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Open the file in write mode. In this case, we're writing the contents into the file.
with open(givenFilename, 'w') as givenfilecontent:
        # Iterate in the above given list using the for loop
        for itr in gvn_lst:
                # Write the iterator value(list elements) into the file using the write() function
                givenfilecontent.write("%s\n" % itr)

# Open the file in read-only mode. In this case, we're simply reading the contents of the file.
filecontent = open("samplefile.txt")
# Read the above file using the read() function(get the content) and print it.
print(filecontent.read())

Output:

hello 
this
is 
Btechgeeks 
good morning

File Content (samplefile.txt):

hello 
this 
is 
Btechgeeks 
good morning

Method #2: Using For Loop (User Input)

Approach:

  • Give the list as user input using the list(),map(),split(),int functions and store it in a variable.
  • Make a single variable to store the path of the file. This is a constant value. This value must be replaced with the file path from your own system in the example below.
  • Open the file in write mode. In this case, we’re writing the contents into the file.
  • Iterate in the above-given list using the for loop.
  • Write the iterator value(list elements) into the file using the write() function.
  • Open the file in read-only mode. In this case, we’re simply reading the contents of the file.
  • Read the above file using the read() function(get the content) and print it.
  • The Exit of Program.

Below is the implementation:

# Give the list as user input using the list(),map(),split(),
# int functions and store it in a variable.
gvn_lst = input("Enter some random list elements separated by spaces = ")
# Make a single variable to store the path of the file. This is a constant value. 
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Open the file in write mode. In this case, we're writing the contents into the file.
with open(givenFilename, 'w') as givenfilecontent:
        # Iterate in the above given list using the for loop
        for itr in gvn_lst.split():
                # Write the iterator value into the file using the write() function
                givenfilecontent.write("%s\n" % itr)

# Open the file in read-only mode. In this case, we're simply reading the contents of the file.
filecontent = open("samplefile.txt")
# Read the above file using the read() function(get the content) and print it.
print(filecontent.read())

Output:

Enter some random list elements separated by spaces = welcome to btechgeeks
welcome
to 
btechgeeks

File Content (samplefile.txt):

welcome
to 
btechgeeks

Google Colab Images:

Files and Code:

Python Program to Find the Most Repeated Word in a Text File

Python Program to Find the Most Repeated Word in a Text File

Given a text file, the task is to find the most repeated word in the given text file in Python.

Program to Find the Most Repeated Word in a Text File

Approach:

  • import the Counter from the collections module using the import keyword.
  • Make a single variable to store the path of the file. This is a constant value. This value must be replaced with the file path from your own system in the example below.
  • Take an empty list to store all the words.
  • Open the file in read-only mode. In this case, we’re simply reading the contents of the file.
  • Iterate through the lines of the file using the For loop.
  • Split the words of the line using the split() function and store them in a variable(it is of type list).
  • Loop in the above list using another Nested For loop.
  • Add the words to the list using the append() function.
  • Get the frequency of all the words using the Counter() function and store it in a variable(of type dictionary).
  • Take a variable to store maximum frequency and initialize its value to 0.
  • Traverse in the frequency dictionary using the For loop
  • Check if the frequency of the word is greater than maximumfreq using the if conditional statement
  • If it is true then set maximumfreq to the corresponding value of the key.
  • Take a variable to store the maximum frequency key.
  • Print the maximum frequency element.

Below is the implementation:

# import the Counter from collections module using the import keyword
from collections import Counter
# Make a single variable to store the path of the file. This is a constant value.
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Take a empty list to store all the words
l = []
# Open the file in read-only mode. In this case, we're simply reading the contents of the file.
with open(givenFilename, 'r') as givenfilecontent:
    # Iterate through the lines of the file using the For loop.
    print('The words in the given file : ')
    for gvnfileline in givenfilecontent:
      # Split the words of the line using the split() function and store them in a variable(it is of type list).
        gvnfilewords = gvnfileline.split()
        # Loop in the above list using another Nested For loop
        for words in gvnfilewords:
          # Add the words to the list using the append() function.
            l.append(words)
# Get frequency of all the words using the Counter() function and store it in a variable(of type dictionary)
freqword = Counter(l)
# Take a variable to store maximum frequency
maximumfreq = 0
# Traverse in the frequency dictionary using the For loop
for i in freqword:
    # Check if the frequency of the word is greater than maximumfreq using the if conditional statement
    if(freqword[i] > maximumfreq):
        # If it is true then set maximumfreq to the corresponding value of the key
        maximumfreq = freqword[i]
        # Take a variable to store the maximum frequency key
        maxele = i
# Print the maximum frequency element
print('The Maximum Frequency element in the given Text File {', maxele, '}')

Output:

The words in the given file : 
The Maximum Frequency element in the given Text File { btechgeeks }

Explanation:

  • The file path is stored in the variable ‘file name.’ Change the value of this variable to the path of your own file.
  • Dragging and dropping a file onto the terminal will show its path. The code will not run unless you change the value of this variable.
  • The file will be opened in reading mode. Use the open() function to open a file. The path to the file is the method’s first parameter, and the mode to open the file is the method’s second parameter.
  • When we open the file, we use the character ‘r’ to signify read-mode.
  • The split() method separates all of the words in the given file.
  • We add all the words to the list.
  • We apply the Counter() function to get the frequency of all the words of the given text file.

Samplefile.txt:

hello this is btechgeeks
hello good morning 
this is btechgeeks
btechgeeks btechgeeks

Sample Implementation in google colab:

Python Program to Count the Number of Occurrence of Key-Value Pair in a Text File

Python Program to Count the Number of Occurrence of Key-Value Pair in a Text File

Given a text file that contains the key-Value pair as data the task is to print the Count of each key-value pair using Python.

Program to Count the Number of Occurrence of Key-Value Pair in a Text File in Python

Approach:

  • Import the Counter from the collections module using the import keyword.
  • Make a single variable to store the path of the file. This is a constant value. This value must be replaced with the file path from your own system in the example below.
  • Take an empty list to store all the words.
  • Open the file in read-only mode. In this case, we’re simply reading the contents of the file.
  • Iterate through the lines of the file using the For loop.
  • Remove the newline character (\n) using strip() function and store it in a variable.
  • Inside the For loop append each key-value pair to list using the append() function.
  • Get the frequency of all the key-value pairs using the Counter() function and store it in a variable(of type dictionary).
  • Traverse in the frequency dictionary using the For loop.
  • Print its corresponding key(frequency).

Below is the implementation:

# import the Counter from collections module using the import keyword
from collections import Counter
# Make a single variable to store the path of the file. This is a constant value.
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Take a empty list to store all the words
l = []
print('The Count of frequency of each key-value pair is :')
# Open the file in read-only mode. In this case, we're simply reading the contents of the file.
with open(givenFilename, 'r') as givenfilecontent:
    # Iterate through the lines of the file using the For loop.
    for gvnfileline in givenfilecontent:
        # Remove the newline character (\n) using strip() function and store it in a variable.
        keyval = gvnfileline.strip('\n')
        # Inside the For loop append each key-value pair to list using the append() function.
        l.append(keyval)
# Get frequency of all the words using the Counter() function and store it in a variable(of type dictionary)
freqword = Counter(l)
# Traverse in the frequency dictionary using the For loop
for key in freqword:
  # print its corresponding key(frequency)
    print(key, '->', freqword[key])

Output:

The Count of frequency of each key-value pair is :
btechgeeks:500 -> 3
hello:200 -> 2
good:900 -> 1

Samplefile.txt:

btechgeeks:500
hello:200
hello:200
good:900
btechgeeks:500
btechgeeks:500

Explanation:

  • The file path is stored in the variable ‘file name.’ Change the value of this variable to the path of your own file.
  • Dragging and dropping a file onto the terminal will show its path. The code will not run unless you change the value of this variable.
  • The file will be opened in reading mode. Use the open() function to open a file. The path to the file is the method’s first parameter, and the mode to open the file is the method’s second parameter.
  • When we open the file, we use the character ‘r’ to signify read-mode.
  • strip() function removes the newline character.
  • We apply the Counter() function to get the frequency of all the key-value pairs of the given text file.

Sample Implementation in google colab:

Python Program to Count Number of Uppercase, Lowercase, Space in a Text File

Program to Count Number of Uppercase, Lowercase, Space in a Text File

Files in Python:

Python file handling is a way of saving program output to a file or reading data from a file. File handling is a crucial concept in the programming world. File management is used in almost every form of project. Assume you are constructing an inventory management system. You have data in the inventory management system related to sales and purchases, thus you must save that data somewhere. Using Python’s file management, you can save that data to a file. You must be given data in the form of a comma-separated file or a Microsoft Excel file if you wish to conduct data analysis. Using file handling, you can read data from a file and write output back into it.

Given a file, the task is to count the number of uppercase, lowercase, spaces in a given file in Python.

Program to Count Number of Uppercase, Lowercase, Space in a Text File in Python

Below is the full approach for counting the number of uppercase, lowercase, spaces in a given file in Python.

Approach:

  • Initialize all the uppercase, lowercase, digits, spaces, special characters count to zero.
  • Make a single variable to store the path of the file. This is a constant value. This value must be replaced with the file path from your own system in the example below.
  • Pass the given filename, r (represents read-only mode) as arguments to the open() function to open the given file.
  • Iterate in the above text of the file using the for loop.
  • Iterate in the characters of the line using nested for loop.
  • Check if the ASCII value of character is greater than or equal to ‘A’ and less than or equal to ‘Z’ using the if conditional statement.
  • If it is true then increment the uppercase count value by 1.
  • Check if the ASCII value of character is greater than or equal to ‘a’ and less than or equal to ‘z’ using the elif conditional statement.
  • If it is true then increment the lowercase count value by 1.
  • Check if the character is greater than 0 and less than or equal to ‘9’ using the elif conditional statement.
  • If it is true then increment the digit count value by 1.
  • Check if the character is equal to space(‘ ‘) using the elif conditional statement.
  • If it is true then increment the spaces count value by 1.
  • Else increment the special characters count value by 1.
  • Print the number of uppercase characters in a given file.
  • Print the number of lowercase characters in a given file.
  • Print the number of digits in a given file.
  • Print the number of spaces in a given file.
  • Print the number of special characters in a given file.
  • The Exit of Program

Below is the implementation:

# Initialize all the uppercase, lowercase, digits, spaces, special characters count to zero.
uppr_cnt = lwr_cnt = dig_cnt = space_cnt = spclchrs_cnt = 0
# Make a single variable to store the path of the file. This is a constant value.
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Pass the given filename, r (represents read-only mode) as arguments to the open() function
# to open the given file
file = open(givenFilename, "r")
# Iterate in the above text of the file using the for loop
for line in file:
    # Iterate in the characters of the line using nested for loop
    for charactrs in line:
        # Check if the ASCII value of character is greater than or equal to 'A' and less than or equal to 'Z'
        # using the if conditional statement.
        if charactrs >= 'A' and charactrs <= 'Z':
            # If it is true then increment the uppercase count value by 1
            uppr_cnt = uppr_cnt+1
        # Check if the ASCII value of character is greater than or equal to 'a' and less than or equal to 'z'
        # using the elif conditional statement.
        elif charactrs >= 'a' and charactrs <= 'z':
            # If it is true then increment the lowercase count value by 1
            lwr_cnt = lwr_cnt+1
        # Check if the character is greater than 0 and less than or equal to '9'
        # using the elif conditional statement.
        elif charactrs > '0' and charactrs <= '9':
            # If it is true then increment the digit count value by 1
            dig_cnt = dig_cnt+1
        # Check if the character is equal to space(' ')
        # using the elif conditional statement.
        elif charactrs == ' ':
            # If it is true then increment the spaces count value by 1
            space_cnt = space_cnt+1
        else:
            # Else increment the special characters count value by 1
            spclchrs_cnt = spclchrs_cnt+1
# Print the number of uppercase characters in a given file        
print("The number of uppercase characters =", uppr_cnt)
# Print the number of lowercase characters in a given file   
print("The number of lowercase characters =", lwr_cnt)
# Print the number of digits in a given file 
print("The number of digits in a given file =", dig_cnt)
# Print the number of spaces in a given file 
print("The number of spaces in a given file =", space_cnt)
# Print the number of special characters in a given file
print("The number of special characters in a given file=", spclchrs_cnt)

Output:

The number of uppercase characters = 3 
The number of lowercase characters = 24 
The number of digits in a given file = 6 
The number of spaces in a given file = 6 
The number of special characters in a given file= 3

File Content:

GoodMorning 123 this is 567 Btechgeeks @#%

Google Colab Images:

Files and Code:

Output:

 

Python Program to Print Just the Last Line of a Text File

Program to Print Just the Last Line of a Text File

Files in Python:

One of the most important subjects for programmers and automation testers is Python file handling (also known as File I/O). It is necessary to work with files in order to write to or read data from them.

Also, if you didn’t know, I/O operations are the most expensive processes where a program can go wrong. As a result, you must use extreme caution while implementing file processing for reporting or any other reason. Optimizing a single file action can help in the creation of a high-performing application or a reliable automated software testing solution.

Consider the following scenario: you’re planning to construct a large Python project with a large number of workflows. Then it’s unavoidable that you don’t make a log file. You’ll also be handling the log file’s read and write activities. Debugging huge applications with log files is a terrific way to go. It’s usually better to consider a scalable design from the start, as you won’t be sorry later if you didn’t.

Given a file, the task is to print only the last line of the given File.

Program to Print Just the Last Line of a Text File in Python

Below is the full approach for printing just the last line of the given File

Approach:

  • Make a single variable to store the path of the file. This is a constant value. This value must be replaced with the file path from your own system in the example below.
  • Open the file in read-only mode. In this case, we’re simply reading the contents of the file.
  • Get the list of lines using the readlines() function and store it in the variable.
  • Print the last line of the given file using negative indexing.
  • The Exit of Program.

Below is the implementation:

# Make a single variable to store the path of the file. This is a constant value. 
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Open the file in read-only mode. In this case, we're simply reading the contents of the file.
with open(givenFilename, 'r') as givenfilecontent:
    # Get the list of lines using the readlines() function and store it in the a variable.
    list_of_lines = givenfilecontent.readlines()
    # Print the last line of the given file using negative indexing
    print("The last line of the given file is:")
    print(list_of_lines[-1])

Output:

The last line of the given file is:
welcome to btechgeeks

File Content:

GoodMorning 123 this is 567 Btechgeeks @#%
hello this is Btechgeeks
welcome to btechgeeks

Explanation:

  • The file path is stored in the variable ‘file name.’ Change the value of this variable to the path of your own file.
  • Dragging and dropping a file onto the terminal will show its path. The code will not run unless you change the value of this variable.
  • The file will be opened in reading mode. Use the open() function to open a file. The path to the file is the method’s first parameter, and the mode to open the file is the method’s second parameter.
  • When we open the file, we use the character ‘r’ to signify read-mode.
  • readlines() function returns all the lines of the file as a list.
  • We Print the last element of the list using negative indexing.

Google Colab Images:

Files and Code:

Python Program to Read Lines from Text File and Display those Lines of Length More than 25

Program to Read Lines from Text File and Display those Lines of Length More than 25

Files in Python:

One of the most important subjects for programmers and automation testers is Python file handling (also known as File I/O). It is necessary to work with files in order to write to or read data from them.

Also, if you didn’t know, I/O operations are the most expensive processes where a programme can go wrong. As a result, you must use extreme caution while implementing file processing for reporting or any other reason. Optimizing a single file action can help in the creation of a high-performing application or a reliable automated software testing solution.

Consider the following scenario: you’re planning to construct a large Python project with a large number of workflows. Then it’s unavoidable that you don’t make a log file. You’ll also be handling the log file’s read and write activities. Debugging huge applications with log files is a terrific way to go. It’s usually better to consider a scalable design from the start, as you won’t be sorry later if you didn’t.

Given a file, the task is to read lines from the given file and print those lines of length(characters) more than 25 in Python

Program to Read Lines from Text File and Display those Lines of Length More than 25 in Python

Below is the full approach for reading lines from the given file and printing those lines of length(characters) more than 25 in Python.

Approach:

  • Make a single variable to store the path of the file. This is a constant value. This value must be replaced with the file path from your own system in the example below.
  • Pass the given filename, r (represents read-only mode) as arguments to the open() function to open the given file.
  • Iterate in the lines of the file using the for loop.
  • Calculate the length of the line using the len() function and store it in a variable.
  • Check if the length of the line is greater than 25 using the if conditional statement.
  • If it is true, then print that respective line.
  • The Exit of Program

Below is the implementation:

# Make a single variable to store the path of the file. This is a constant value. 
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Pass the given filename, r (represents read-only mode) as arguments to the open() function
# to open the given file
file = open(givenFilename,"r")
print("The lines having more than 25 characters are:")
# Iterate in the lines of the file using the for loop
for lines in file:
    # Calculate the length of the line using the len() function and store it in a variable.
    line_len=len(lines)
    # Check if the length of the line is greater than 25 using the if conditional statement
    if line_len>25:
        # If it is true, then print that respective line.
        print(lines)

Output:

The lines having more than 25 characters are: 
GoodMorning 123 this is 567 Btechgeeks @#% 

hello this is Btechgeeks.welcome all

Explanation:

  • The file path is stored in the variable ‘file name.’ Change the value of this variable to the path of your own file.
  • Dragging and dropping a file onto the terminal will show its path. The code will not run unless you change the value of this variable.
  • The file will be opened in reading mode. Use the open() function to open a file. The path to the file is the method’s first parameter, and the mode to open the file is the method’s second parameter.
  • When we open the file, we use the character ‘r’ to signify read-mode.
  • We traverse through the lines of the file using For loop and check the length of the corresponding line using the len() function.
  • We print the lines which are having length greater than 25.

File Content:

hello all
GoodMorning 123 this is 567 Btechgeeks @#%
pythonprograms
hello this is Btechgeeks.welcome all
welcome to btechgeeks
btechgeeks 
pythoncode

Google Colab Images:

Files and Code:

Python Program to Write 1 to 100 in a Text File

Program to Write 1 to 100 in a Text File

Files in Python:

Python file handling is a way of saving program output to a file or reading data from a file. File handling is a crucial concept in the programming world. File management is used in almost every form of project. Assume you are constructing an inventory management system. You have data in the inventory management system related to sales and purchases, thus you must save that data somewhere. Using Python’s file management, you can save that data to a file. You must be given data in the form of a comma-separated file or a Microsoft Excel file if you wish to conduct data analysis. Using file handling, you can read data from a file and write output back into it.

Given a file, the task is to write 1 to 100 numbers into a given file in Python.

Program to Write 1 to 100 in a Text File in Python

Below is the full approach for writing 1 to 100 numbers into a given file in Python.

Approach:

  • Make a single variable to store the path of the file. This is a constant value. This value must be replaced with the file path from your own system in the example below.
  • Open the file in write mode. In this case, we’re writing the contents into the file.
  • Iterate from 1 to 100 using the for loop.
  • Convert the iterator value into a string using the str() function and write it into the file using the write() function.
  • The Exit of Program.

Below is the implementation:

# Make a single variable to store the path of the file. This is a constant value.
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Open the file in write mode. In this case, we're writing the contents into the file.
with open(givenFilename, 'w') as givenfilecontent:
    # Iterate from 1 to 100 using the for loop
    for itr in range(1,101):
        # Convert the iterator value into a string using the str() function and write it into
        # the file using the write() function
        givenfilecontent.write(str(itr) + "\t")

Output:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 
95 96 97 98 99 100

Explanation:

  • The file path is stored in the variable ‘file name.’ Change the value of this variable to the path of your own file.
  • Dragging and dropping a file onto the terminal will show its path. The code will not run unless you change the value of this variable.
  • The file will be opened in writing mode. Use the open() function to open a file. The path to the file is the method’s first parameter, and the mode to open the file is the method’s second parameter.
  • When we open the file, we use the character ‘w’ to signify write-mode.
  • We write the data to file using the write() function.

File Content Before Writing:

hello this is btechgeeks sample file specific
python codes Summary

File Content After Writing 1 to 100:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 
95 96 97 98 99 100

Note:

It erases all the previous file content and overwrites into it

Google Colab Images:

Files and Code: