本地日记交换记录

目标

  • 一次接收输入一行日记
  • 保存为本地文件
  • 再次运行系统时,能打印出过往的所有日记

思路

脚本调用

  • 猜测是需要import一个脚本(版本一没有用到)

参数调用

  • sys 中的 argv,可以用来调用脚本,也可以直接做录入日记

输入中文

  • 其中一个办法是用 UTF-8, 支持所有语言
  • 比如用,# -- coding: encoding --

持续交互

  • 考虑到用持续用raw_input()提示输入文字

文字输入

  • file.open(), file.read()

实现的过程

版本一雏形

# -*- coding: utf-8 -*-
import sys

script, file_name = sys.argv

read_txt = open(file_name, 'r')
print "History records: \n %r" % read_txt.read()

先在main.py的目录下建了一个文件夹,随便录入一些汉字用来测试

  • $ python main.py diary.txt
    History records: '\xe5\xae\x9d\xe8\xb4\x9d\xe5\xae\x9d\xe8\xb4\x9d\xe5\x96\x9c\xe6\xac\xa2\xe4\xbd\xa0'

  • 直接 print read_txt.read() 却正常显示
    把%r换成%s,汉字显示正常

录入

  • 持续录入
  • 错误更改
  • 退出(空行)
write_txt = open(file_name,'a+')
def start():
    while True:
        line = raw_input('>')
        if line == 'quit':
            quit_txt()
        elif line == 'c':
            line = raw_input('>>')
            write_txt.write(line)
            print "changed"
        else:
            write_txt.write(line)

def quit_txt():
    write_txt.write('\n\n\n')
    write_txt.close()
    print 'Bye'

    exit(1)

start()

更改命令并不能正常工作

  • 之前的文字会同更改后的文字一同写入文件

版本二


考虑到想要自己添加时间和关键字:

in_put = sys.argv[1:]

file_path = "/Users..../diary.py"
temp_file_path = "/Users/...../temp_file.txt"
temp_file = open(temp_file_path, 'a+')

txt = open(file_path,'a+')
txt.seek(0)
print txt.read()

for i in in_put:
    txt.write(i+',')
txt.write('\n\n')
  • 用'a+'打开文件,指针位置是在文件的末尾,所以需要用seek(0)调回来,才能从头read文件

简化了start()函数:

def start():
    while True:
        line = raw_input('>>>')        
        if line == 'save':
            save()
        elif line == 'alter':
            alter()
        else:
            temp_file.write(line+'\n')

修改了alter函数:

  • 功能:输入alter,删除上一行的录入内容
    • 把line write到一个临时文件temp_file
    • 每次执行alter时,读取temp_file哪除上一行的所有内容
    • truncate temp_file
    • 再把读取的内容录入temp_file中,实现删的功能
def alter():
    temp_file.seek(0)
    all_lines = temp_file.readlines()
    last_line = all_lines[len(all_lines)-1]

    temp_file.seek(0)
    temp_file.truncate()
    for i in all_lines:        
        if i != last_line:
            temp_file.write(i)
    print 'Altered'

问题:

  • 一定注意到文件被执行到什么位置了,再执行新的操作时要rewind,即使是truncate
  • readlines后,输出的是一个list

修改了quit函数:

  • 考虑到即时写入的line可能会被修改,line先被存放在temp_file中
  • 在执行此函数时,把temp_file的内容录入diary.py中
def save():
    temp_file.seek(0)
    save_lines = temp_file.readlines()
    for i in save_lines:
        txt.write(i)
    txt.write('\n\n\n')
    temp_file.seek(0)
    temp_file.truncate()
    temp_file.close()
    txt.close()
    print 'Bye'


    exit(1)

小结

  • 没有搞明白CLI怎么用
  • 没有加入自动时间录入
  • 迭代的过程并没有清晰的记录下来
  • 每次添加一个功能,都编辑个简单的代码测试一下,但何时添加seek(0)需要注意

版本三

  • 增加了时间
  • 增加了一个函数quit
    • 在输入quit时,所有录入保存在temp_file中
    • 输入save,把temp_file中的内容录入diary中,并在开头增加时间

这里是代码