HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Python text appender

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
appendertextpython

Problem

The aim of it is to be the quickest way to add to existing notes via SSHh.

Is this code in Python style? Am I missing any methods that would make the code simpler or legible?

#! /usr/bin/python3

#Maintain: myemail@mail.com
#Purpose: A simple way to add entries to existing files
#Usage: Write the name of the file you intend to add to.
#Future: A list of editable files when the program opens

from sys import argv
import datetime
import os,errno
import os.path
import contextlib

script, typed = argv
filename = typed+".txt"
savelocation = os.path.join('/home/user/',filename)
print(savelocation)
print("Aditor: a digital typewriter, Type: d when done")

date = str(datetime.datetime.now().date())
with open("/tmp/tempfile.txt","a+") as target:
        target.write("\n")
        target.write(date)
        while True:
                entry=input()
                target.write("\n")
                if entry in ['done','d']: 
                        break
                else:
                        target.write(entry)

target = open("/tmp/tempfile.txt","r")
f = open(filename, "a")
f.write(target.read())

f.close()
target.close()
print("Entry saved.")

with contextlib.suppress(FileNotFoundError):
    os.remove("/tmp/tempfile.txt")

Solution

If you don't want to write to the file directly and want to "apply" the changes at once, instead of writing to a temp file, you can keep the changes in memory - in a list of strings:

from sys import argv
from datetime import datetime
import os

if __name__ == '__main__':
    _, typed = argv
    filename = typed + ".txt"
    save_location = os.path.join('/home/user/', filename)

    print(save_location)
    print("Aditor: a digital typewriter, Type: d when done")

    date = datetime.now().strftime("%Y/%m/%d")

    cache = ["\n", date]
    while True:
        entry = input()
        cache.append("\n")

        if entry == 'done' or entry == 'd':
            break

        cache.append(entry)

    with open(save_location, "a") as f:
        f.writelines(cache)


Note that I've removed everything related to handling the temp file.

Also there were some other changes applied in the code above:

  • using 4 spaces for indentation



  • used _ for a "throwaway" variable (the script name is not used)



  • fixed the variable naming - words need to be separated with an underscore - save_location instead of savelocation (PEP8 reference)



  • checking for "done" using simple comparisons with done and d



  • using strftime() to dump a datetime into string



  • putting the code to under if __name__ == '__main__': to avoid the code to be executed if imported



  • organized imports per PEP8 (reference)

Code Snippets

from sys import argv
from datetime import datetime
import os


if __name__ == '__main__':
    _, typed = argv
    filename = typed + ".txt"
    save_location = os.path.join('/home/user/', filename)

    print(save_location)
    print("Aditor: a digital typewriter, Type: d when done")

    date = datetime.now().strftime("%Y/%m/%d")

    cache = ["\n", date]
    while True:
        entry = input()
        cache.append("\n")

        if entry == 'done' or entry == 'd':
            break

        cache.append(entry)

    with open(save_location, "a") as f:
        f.writelines(cache)

Context

StackExchange Code Review Q#158842, answer score: 4

Revisions (0)

No revisions yet.