Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Reading and writing file on MAC with Python

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 4.50k
    Comment on it

    Hi All ,

     

    Some time we have to create a file to store some data for our application and also read that file whenever we need it. So in this tutorial we will learn how to create a file on MAC system using python and also reading and writing on file.

     

    1) Create a file :- In this function we just have to provide PATH and FILE_NAME. Please avoid to use private path where special permission is required.

    def createFile(path,filename):
        name = path+'/'+filename  # Name of text file coerced with +.txt 
        try:
            file = open(name,'a')   # Trying to create a new file or open one
            file.close()
    
        except:
            print('Something went wrong! Can\'t tell what?')
            sys.exit(0) # quit Python

     

    2) Write some content to file :- In this function we just have to provide PATH and get user input .User must press enter to finish his input to file.

    def writeToFile(path):
        try:
            file = open(path,'a') 
            addToFile = raw_input("please add content to file : ")
            file.write("\n" + addToFile)
            file.close()
    
        except:
            print('Something went wrong! Can\'t tell what?')
            sys.exit(0) # quit Python

     

    3) Read from file :- In this function we just have to provide PATH and you can see file content on you terminal.

    def readFromFile(path):
        try:
            file = open(name,'r')
            with file as ins:
        		array = []
        		for line in ins:
            		array.append(line)
            	print(array)
            file.close()
    
        except:
            print('Something went wrong! Can\'t tell what?')
            sys.exit(0) # quit Python

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: