如何让我的python程序编写新文件

时间:2018-05-08 13:53:32

标签: python-3.x persistence

我正在编写一个程序,通过该程序我可以从文件中提取数据,然后根据某些条件,我必须将该数据写入其他文件。这些文件不存在,只有代码才会创建这些新文件。我已经尝试了所有可能的打印参数组合,但没有任何帮助。该程序似乎运行良好,IDLE没有错误,但没有创建新文件。有人可以给我一个解决方案吗?

这是我的代码:

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")

1 个答案:

答案 0 :(得分:1)

2个问题

  1. 你应该使用

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

    w + - 如果文件不存在则创建文件并在写入模式下打开

         

    模式'r +','w +'和'a +'打开文件进行更新(读写);请注意'w +'截断文件..

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

    2

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

    如果sketch.txt文件不存在,那么“man”和“other”将不会被初始化 并且在print方法中会抛出另一个异常

    尝试运行此脚本

    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()