import os
class File: ##File is class name
def readTextFile(self,filename):
self.filename = filename
try:
self.file = open(filename, 'r') ## opening the file in reading mode.
except:
print('{} not found'.format(self.filename)) ##if file is not found.
return False
self.content = self.file.read() ## readlines() function returns the list of all lines.
self.file.close() ## closeing the file
return self.content ## print the content of text file
def createNewFile(self,filename='input.txt',content=''):
self.filename=filename
self.content=content
self.filepath='/'.join(filename.split('/')[:-1]) ##spliting filepath from file name
if self.filepath=='': ##If not found then initilize as current directery.
self.filepath='.'
self.listOfFile=os.listdir(self.filepath)
##checking file already exist or not.
self.check=False
if self.filename in self.listOfFile:
self.message=input('{} already exist. Do you want to overwrite. Y or N:'.format(self.filename))
if self.message=='Y' or self.message=='y': ##taking user confermation for overwrite file
self.check=True
else:
self.check=False ## If user denied to overwrite file
print('Copied Failed. Try Again')
else:
self.check=True
if self.check==True:
self.file = open(filename, 'w') ## new opening file
self.file.write(self.content) ## put the content in file
self.file.close() ##closeing file
print('Copied Done')
def main():
f = File() ##creating objectof 'File' class named as f
filename1 = input('Enter Source File Name:') ##taking user input of file name
content=f.readTextFile(filename1) ## call the method of File class
if content is False:
print('copying failed...Try again')
## if source file is found
else:
filename2=input('Enter New File Name:')
##put the text in new file
f.createNewFile(filename2,content)
if __name__=='__main__':
main()
Dependencies of this output:
A text file in current directory named as 'input.txt'.
Output:
Enter Source File Name:input.txt
Enter New File Name:output.txt
Copied Done
Comments
Abhay
31-May-2019 01:28:17 PM