python在txt_file中的现有行之间添加文本

时间:2017-02-23 05:41:05

标签: python

我正在尝试制作一个简单的日记程序来练习。每当我写日记时都要添加行。日记将在“完成”或“完成”行

之前继续输入
contents[0] Diary_file

contents[1] 'empty'

contents[2] 'Start line'

contents[3] '----------------------------'

contents[4] Diary No.1 **<- first diary starts from here**

contents[5] "I had a good day
...

===============================

(for counting logic)

diary counts                    
0

CODE

def writing():
content = (raw_input("> "))
return content

def put_between(word):
    with open("D_diary.txt", 'r') as read_file: # before start, get last diary
        contents = read_file.readlines()        # get contents in list
        for i in contents:
            if i == 'finish' or i == 'Finish':  #get the last diary finish line
                finish_line = i                 #to get next starting point
            else:
                finish_line = 2                 #for starting the first diary
        count = contents[-1]                    #getting the diary count number
        print count                             #for creating 'Diary No.%d' %count

    **contents.insert(finish_line+2, word)        #THIS IS THE ACTUAL PROBLEM  
    in_contents = []                            #TRYING TO START WRITING FROM
    with open("D_diary", "w") as write_file:    #
        for i in contents:
            in_contents += '\n'.join(contents) #ERROR PART
            write_file.write(in_contents)**

def writing_logic():
    one_weather = raw_input("Weather : ")                          
    print "Write your Day! -Type 'finish' or 'Finish' to stop\n"  
    while True:
        word = writing()                        #func (just raw_input)
        if word == 'finish' or word == 'Finish':
            break                                   #finish getting text
        else:
            put_between(word)                       #goes up to func

错误:

  

* TypeError:序列项4:期望字符串,找到NoneType

2 个答案:

答案 0 :(得分:0)

您的.cer方法似乎正在返回.cer

您也可以将代码发布到该方法吗?

答案 1 :(得分:0)

put_between功能中,您要将finish_line设置为i,然后再设置为finish_line+2。但是i变量在for i in contents中使用,这意味着它有时(finish_line = i)是一行文本,有时(finish_line = 2)是一个整数。

您可能应该使用.index()方法搜索单词finish,因为您的代码表明它是该行中唯一的单词:

for text in ('Finish', 'finish'):
    try:
        finish_line = contents.index(text)
        break
    except ValueError:
        pass
else:
    finish_line = 2

您从文本中提取count,但未将其转换为整数。您需要使用count = int(...)来获取整数,以便稍后可以count += 1递增它。

你可以通过加入换行来获得输出:

outfile.write('\n'.join(contents))

print('\n'.join(contents), file=outfile)