Showing posts with label File Handling. Show all posts
Showing posts with label File Handling. Show all posts

Java - File handling - String Manipulation - remove unnecessary space between words


// File Handling
// String manipulations

/*
Write a program that copies the content of one file to another by removing unnecessary space between words
*/

import java.io.*;

class Filespace
{
     public static void main(String as[]) throws IOException
     {
          FileReader fr = new FileReader("ipt2.txt");
          FileWriter fw = new FileWriter("opt2.txt");
          BufferedReader br = new BufferedReader(fr);
         
          while(true)
          {
              String str = br.readLine();
             
               if(str==null)
                   break;             
             
              String sa[] = str.split(" ");
             
              for(String s:sa)
              {  
                   s = s.trim();
                   if(s.length()!=0)
                        fw.write(s+" ");
              }
              fw.write("\n");
          }
          fr.close();
          fw.close();
     }
}

File Handling - File Properties

// File Handling
// File Properties

/*
Write a Java program that reads a file name from the user, displays information about whether the file exists, whether the file is readable, or writable, the type of file and the length of the file in bytes.
*/

import java.io.*;

class FileHandling
{
     public static void main(String as[]) throws IOException
     {
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
          System.out.print("Enter string : ");
          String str = br.readLine().trim();
         
          File f1 = new File(str);
         
          if (f1.isFile()==true)
          {
             
              System.out.println("File exists = " + f1.exists());
             
              System.out.println("File name = " + f1.getName());
              System.out.println("Parent File = " + f1.getParent());
             
              System.out.println("File path = " + f1.getPath());
              System.out.println("If absolute path of file is specified = "+f1.isAbsolute());
              if(f1.isAbsolute()==true)
                   System.out.println("File absolute path = "+f1.getAbsolutePath());
             
              System.out.println("File type = " + str.substring(str.lastIndexOf('.')));
    
    
              System.out.println("File readable = " + f1.canRead());
              System.out.println("File writable = " + f1.canWrite());      
             
              System.out.println("File last modified = " + f1.lastModified());
                  
              System.out.println("File length = " + f1.length() + " bytes");

              }       
          else
              System.out.println("Not a file");
     }
}



/*

Sample output:

     D:\oopjava\iostreams>javac FileHandling.java
     D:\oopjava\iostreams>java FileHandling

     Enter string : FileHandling.java
     File exists = true
     File name = FileHandling.java
     Parent File = null
     File path = FileHandling.java
     If absolute path of file is specified = false
     File type = .java
     File readable = true
     File writable = true
     File last modified = 1537860249825
     File length = 1396 bytes

     D:\oopjava\iostreams>


*/

File handling - Command Line Arguments - Line count

// File handling
// Command Line Arguments

/*
Write a Java program LineCounts.java that will count the number of lines in each files that is specified on the command line. Note that multiple files can be specified, as in               
    
     java LineCounts file1.txt file2.txt file3.txt
*/

import java.io.*;

class LineCounts
{
     public static void main(String as[]) throws IOException
     {
          for(int i=0;i<as.length;i++)
          {
              FileReader fr = new FileReader(as[i]);
              BufferedReader br = new BufferedReader(fr);
              int linecount=0;
              while(true)
              {
                   String str = br.readLine();
                   if(str==null)
                        break;
                  
                   linecount++;
              }
              fr.close();
              System.out.println(as[i]+" = "+linecount);
          }
     }
}

Java - File handling - line, word and character count


// File handling

/*
Write a Java program that displays the number of characters, lines and words in a text file.
*/

import java.io.*;

class FileLWC
{
     public static void main(String as[]) throws IOException
     {
         
          FileInputStream fin = new FileInputStream("ipt.txt");
          int lc = 0, wc = 0, cc = 0;
         
          while(true)
          {
              int i = fin.read();
              if(i==-1)
              {
                   lc++;
                   wc++;
                   break;
              }
              char c = (char)i;
             
              if(c=='\n' || c=='.')
              {
                   lc++;
                   wc++;
              }
              else if(c=='\t' || c==' ')
                   wc++;
              else if((c>='a' && c<='z')||(c>='A' && c<='Z'))
                   cc++;
                            
          }       
          System.out.println("Line count = "+lc);
          System.out.println("Word count = "+wc);
          System.out.println("Character count = "+cc);
          fin.close();
     }
}

Java - File handling - display file with line number

// File handling

/*
Write a Java program that reads a file and displays the file on the screen, with a line number before each line.
*/

import java.io.*;

class FileLineDisplay
{
     public static void main(String as[]) throws IOException
     {
          FileReader fr = new FileReader("ipt.txt");
          BufferedReader br = new BufferedReader(fr);

          int linecount=1;

          while(true)
          {
              String str = br.readLine();
              if(str==null)
                   break;
              System.out.print(linecount+" "+str+"\n");
              linecount++;
          }
          fr.close();
     }
}

PYTHON ASSIGNMENT 9: FILES




Read from console and write to file

Read from file and display in console

Display file content with line number

Display first N lines of a file

Display nth line of a file

Display from nth line to mth line of a file

Copy file

Copy first N lines from a file to new file

Copy from nth line to mth line of a file to new file

Merge two files

Count number of characters, words and lines in a file

Search if a word exists in a file.

Count number of times a word exists in a file

Search if a word exists in a file. Display all lines in which the word exists.

Delete a word in a file

Replace a word in a file

Write a program that creates a dictionary of the frequency of all words in a file. Remove noise words like “the”, “and”, and so on. Display the three most frequently occurring words.

Write a program that creates a dictionary of the frequency of all the characters in a file. Display five most frequently occurring characters.

Given a file containing customer names and their phone numbers, write a program to find the telephone number of a given customer.

Compare two files and print the first line where they differ.




File Handling 21: Read and write to file. student details

# Read student details and write to file

fs = open("stu.txt","w+")

NumStu = int(input("Enter number of students : "))
counter = 0
while(counter<NumStu):
    name = input("Enter name : ").strip()
    rno = int(input("Enter number : "))
    cgpa = float(input("Enter cgpa : "))
   
    fs.write(name+" "+str(rno)+" "+str(cgpa)+"\n")

    counter+=1


print("Displaying student details:")
fs.seek(0,0)
while(True):
    line = fs.readline()
    if not line:
        break
    print(line)
fs.close()

File handling 18: Files and dictionary, Histogram, character frequency

# Write a program that creates a dictionary
# of the frequency of all characters in a file.
# display five most frequently occuring characters

# Files, Dictionary and Command line arguments
# Histogram - Character frequency

import sys
import operator

fname = sys.argv[1]
fs = open(fname, "r")

Char_freq = {}

while(True):
    Line = fs.readline().strip().lower()
   
    if not Line:
        break
   
    for ch in Line:
        if (ch.isalpha()):
            if ch in Char_freq:
                Char_freq[ch] += 1
            else:
                Char_freq[ch] = 1
           
for ch in Char_freq:
    print(ch, Char_freq[ch])

List1 = sorted(Char_freq.items(), key=operator.itemgetter(1), reverse=True)

print("Five most frequently occuring characters :")
for k,v in List1[0:5]:
    print(k,v)

fs.close()

File Handling 19: Name and phone number

# Given a file containing customer names and their phone numbers, 
# write a program to find the telephone number of a given customer.

# Files: Name and phone number
import sys

fname = sys.argv[1]
fs = open(fname,"r")
Flag = False

Name = input("Enter name :")
Name = Name.strip().lower()

while(True):
    line = fs.readline()
   
    if not line:
        break
   
    L = line.split(" ")
    if(L[0].strip().lower() == Name):
        Flag = True
        print("Name =", Name.capitalize())
        print("Phone number =", L[1])
        break

if(Flag==False):
    print(Name, "- Name not found in directory")
fs.close()

File handling 20: Compare two files and print the line where they differ

# Files: Difference between files

import sys

try:
    fname1 = sys.argv[1]
    fname2 = sys.argv[2]

    fs1 = open(fname1,"r")
    fs2 = open(fname2,"r")
    Flag = False
  
    L1 = fs1.readlines()
    L2 = fs2.readlines()

    nlines = min(len(L1), len(L2))

    for idx in range(0, nlines, 1):
        if (L1[idx] != L2[idx]):
            print("Files differ at line number", idx+1)
            Flag = True
            break
          
    if(Flag == False):
        if(len(L1)==len(L2)):
            print("Files are the same. They do not differ")
        else:
            print("Files differ at line number", nlines+1)
except:
    print("Error")
  
finally:  
    fs1.close()
    fs2.close()



File Handling 17: Files and Dictionary: Histogram, Word Frequency, remove noise words

# Write a program that creates a dictionary
# of the frequency of all words in a file.

# Files, Dictionary and Command line arguments
# Histogram - Word frequency

import sys

fname = sys.argv[1]
fs = open(fname, "r")

Word_freq = {}

while(True):
new_Line = ""
Line = fs.readline().strip().lower()

if not Line:
break

for ch in Line:
if (ch.isalpha() or ch.isspace()):
new_Line+=ch
L = new_Line.split(" ")

for wd in L:
if wd in Word_freq:
Word_freq[wd] += 1
else:
Word_freq[wd] = 1

for ele in Word_freq:
print(ele.ljust(15), Word_freq[ele])

print("Number of unique words in file = ", len(Word_freq))

fs.close()




# Write a program that creates a dictionary
# of the frequency of all words in a file.
# Remove noise words in file like a, an, the etc

# Files, Dictionary and Command line arguments
# Histogram - Word frequency

import sys

fname = sys.argv[1]
fs = open(fname, "r")

Word_freq = {}

Noise_words = ['an', 'as', 'of', 'it','by',  'to', 'so', 'do', 'be', 'up', 'on', 'ie', 'its', 'are', 'all', 'has', 'can', 'how', 'end', 'any', 'may', 'for', 'will', 'use', 'one', 'two', 'the', 'also', 'have', 'this', 'that', 'what', 'where', 'when', 'then', 'those', 'from', 'once', 'more', 'most' ]

while(True):
new_Line = ""
Line = fs.readline().strip().lower()

if not Line:
break

for ch in Line:
if (ch.isalpha() or ch.isspace()):
new_Line+=ch
L = new_Line.split(" ")

for wd in L:
if (len(wd)<=1 or wd in Noise_words):
continue

if wd in Word_freq:
Word_freq[wd] += 1
else:
Word_freq[wd] = 1

for ele in Word_freq:
print(ele.ljust(15), Word_freq[ele])

print("Number of unique words in file = ", len(Word_freq))

fs.close()

File handling 16: Replace a word in file

# Replace a word in a file

fs = open("ipt.txt", "r+")
old_str = input("Enter string to replace : ").strip()
new_str = input("Enter new string : ").strip()

Line = fs.read()
Line = Line.replace(old_str, new_str)

fs.seek(0,0)
fs.truncate()
fs.write(Line)

fs.seek(0,0)
Line = fs.read()
print(Line)

fs.close()

File Handling 15: Delete word in file

# Delete a word in a file

fs = open("ipt.txt", "r+")
search_str = input("Enter string to search : ").strip()

Line = fs.read()
Line = Line.replace(search_str, "")

fs.seek(0,0)
fs.truncate()
fs.write(Line)

fs.seek(0,0)
Line = fs.read()
print(Line)

fs.close()

File handling 14: display line containing word in file

# Search if a word exists in a file.
# Display all lines in which the word exists.

fs = open("ipt.txt", "r")
search_str = input("Enter string to search : ").strip().lower()
Flag = False

while(True):
Line = fs.readline().strip().lower()

if not Line:
break

if (search_str in Line):
Flag = True
print(Line)

if(Flag==False):
print(search_str, "not present in file")

fs.close()

File Handling 13: Count number of occurances of a word in a file

# Count number of times a word exists in a file

fs = open("ipt.txt", "r")
search_str = input("Enter string to search : ").strip().lower()
counter = 0

while(True):
Line = fs.readline().strip().lower()

if not Line:
break

counter += Line.count(search_str)

if(counter):
print(search_str, "present in file", counter , "times")
else:
print(search_str, "not present in file")

fs.close()

File handling 12: file word search

# Search if a word exists in a file.

fs = open("ipt.txt", "r")
search_str = input("Enter string to search : ").strip()
Flag = False

while(True):
Line = fs.readline().strip()

if not Line:
break

if (search_str in Line):
Flag = True
break

if(Flag==True):
print(search_str, "present in file")
else:
print(search_str, "not present in file")

fs.close()

File Handling 11: File line, word and character count

# Count number of characters, words and lines in a file
# File Count

fs = open("ipt.txt", "r")

charcount = 0
wordcount = 0
linecount = 0

all_lines = fs.readlines()
linecount = len(all_lines)

for Line in all_lines:
Line = Line.strip().lower()

tmp = Line.split(" ")
wordcount += len(tmp)

for ch in Line:
if(ch.isalpha()):
charcount += 1

print("Number of characters in file =", charcount)
print("Number of words in file =", wordcount)
print("Number of lines in file =", linecount)

fs.close()