Python – Check file, truncate file, insert lines to a file, copy one file to another file

This python script demonstrates how to:

  • Check if files exist or not
  • If a file is empty or not
  • How to Truncate a file
  • How to insert lines to a file from the command prompt
  • How to copy one file to another

#!/usr/bin/python
from sys import argv
import os
script, file1, file2 = argv

prompt = "> "

#Variables that store values for if the needed files exist
print "Testing if required files exist"
check_filename_file = os.path.isfile('filename')
check_test_file = os.path.isfile('test')


#Check for if files exist is done here.
if check_filename_file and check_test_file:
	print "All files exist. Will continue with process"
	print "-------------------------------------------"
	print "Press any key to proceed"
	raw_input(prompt)
	#Here we only ead the files and we close them.
	print "Will now read files %s and %s " % (file1, file2)
	file_1 = open(file1)
	file_2 = open(file2)
	print file_1.read()
	print file_2.read()
	file_1.close()
	file_2.close()
	#This is a nested IF. It truncates the file if it is not empty
	if os.stat(file2).st_size > 0:
		print "I will truncate the %s file " % file2
		file_2 = open(file2, 'w')
		file_2.truncate();
		file_2.close()
		#User is asked to enter lines that will be inserted in the second file
		print "Will now enter some lines in file %s " % file2
		line1 = raw_input("Enter a line:")
		line2 = raw_input("Enter a line:")
		line3 = raw_input("Enter a line:")
		
		file_2 = open(file2, 'w')
		file_2.write(line1)
		file_2.write(line2)
		file_2.write(line3)
		file_2.close()
	else:
		print "No need to truncate file"
	#File copying. Both files are being opened (second file with write option). The first file is being read and then file_2 is instructed to be printed into file2
	print "I will now copy file %s to %s" % (file1, file2)
	file_1 = open(file1)
	file_2 = open(file2, 'w')
	file_1_src = file_1.read()
	file_2_dst = file_2.write(file_1_src)
	file_1.close()
	file_2.close()
	

else:
	print "Files are missing"

  •  
Share Button

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.