Search code examples
python-3.xpersistence

How do I make my python program to write a new file


I am writing a program by which I can extract data from a file, and then based on some condition, I have to write that data to other files. These files do not exist and only the code will create these new files. I have tried every possible combination of print parameters but nothing is helping. The program seems to run fine with no error in IDLE but no new files are created. Can somebody give me a solution?

Here is my code:

try:
    data= open('sketch.txt')
    for x in data:
        try:
            (person, sentence)= x.split(':',1)"""data is in form of sentences with: symbol present"""
            man=[]      # list to store person 
            other=[]     #list to store sentence
            if person=="Man":
                man.append(sentence)
            elif person=="Other Man":
                other.append(sentence)
        except ValueError:
            pass
    data.close()
except IOError:
    print("file not found")
    try:
        man_file=open("man_file.txt","w")""" otherman_file and man_file are for storing data"""
        otherman_file=open("otherman_file.txt", "w")
        print(man,file= man_file.txt)
        print(other, file=otherman_file.txt)
        man_file.close()
        otherman_file.close()
    except IOError:
        print ("file error")

Solution

  • 2 problems

    1. you should use

       man_file = open("man_file.txt", "w+")
      otherman_file = open("otherman_file.txt", "w+")
      

    w+ - create file if it doesn't exist and open it in write mode

    Modes 'r+', 'w+' and 'a+' open the file for updating (reading and writing); note that 'w+' truncates the file..

    https://docs.python.org/2/library/functions.html

    2.

      print(man,file= man_file.txt)
      print(other, file=otherman_file.txt)
    

    if sketch.txt file do not exist then "man" and "other" will not initialized and in the print method will throw another exception

    try to run this script

    def func():
        man = []      # list to store person
        other = []  # list to store sentence
        try:
            data = open('sketch.txt', 'r')
            for x in data:
                try:
                    (person, sentence) = x.split(':', 1)
    
                    if person == "Man":
                        man.append(sentence)
                    elif person == "Other Man":
                        other.append(sentence)
                except ValueError:
                    pass
            data.close()
        except IOError:
            print("file not found")
        try:
            man_file = open("man_file.txt", "w+")
            otherman_file = open("otherman_file.txt", "w+")
        #        print(man, man_file.txt)
        #       print(other, otherman_file.txt)
            man_file.close()
            otherman_file.close()
        except IOError:
            print ("file error")
    
    
    func()