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

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

我正在编写一个程序,通过它可以从文件中提取数据,然后根据某些条件,我必须将该数据写入其他文件。这些文件不存在,只有代码会创建这些新文件。我已经尝试了所有可能的打印参数组合,但没有任何帮助。该程序似乎 运行 正常,在 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")

2 个问题

  1. 你应该使用

     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)

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