0

I’m trying to create a notepad on python, with the ability to create an account, log in to that account, create notes, view notes, and edit notes. I know how to append to a specific line in a file by detecting a specific string, but that didn’t work for appending user-generated input to user-generated data in a file. The output should be adding new data onto a specific line, then being able to access it later.

projectnum = int(input(“What line to you want to edit? : “)
user_input = input(“Type what you want to add”)
f = open(user+”.txt”,”a”)
f.write(user_input)

# then I don't know what to do here to specify the line.
sphoenix
  • 3,327
  • 5
  • 22
  • 40
  • Do you mean replace the Nth line of the file with new content and delete the old, or insert a new line atthat offset? – tripleee Jul 24 '20 at 18:11
  • Have you considered re-using whatever logic you have for modifying based on a specific string? You just need to enumerate the lines instead of checking that line for some text – Cireo Jul 24 '20 at 18:12
  • Possible duplicate of https://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python – tripleee Jul 24 '20 at 18:12

3 Answers3

0

An easy way is to read the file's contents, and the go to the line by splitting by lines, and when we reach the desired line, we can do our thing there

projectnum = int(input("What line to you want to edit? : "))
user_input = input("Type what you want to add")

### Read the current file contents
with open(user+".txt", 'r') as ReadFile:
    contents = ReadFile.read()

output = ""

### Read the lines of the file
for idx, line in enumerate(contents.splitlines()):
    if idx == projectnum - 1: # enumerate starts counting from zero, but lines start from 1. IE idx = 0 when line = 1.
        ### Do our thing, for example add to the current line:
        output += line + user_input + "\n"
    else:
        output += line + "\n" # don't forget to add the linebreaks back in

with open(user+".txt", 'w') as WriteFile:
    WriteFile.write(output)
AlpacaJones
  • 114
  • 8
0

Read the data from the file and store it in a list.Then use the list index to make changes to the data.Note this may raise a IndexError

projectnum = int(input('What line to you want to edit? : ')
user_input = input('Type what you want to add')

f = open('file.txt', 'r');
data = f.readlines()
f.close()

data[projectnum] = user_input + "\n"

f = open('file.txt', 'w')
f.writelines(data)
f.close()
denniz crypto
  • 451
  • 4
  • 10
0

Read and then write them after making the changes. However, this is not an ideal solution if the file is too large.

projectnum = int(input("What line to you want to edit? : "))
projectnum = projectnum - 1 if projectnum > 0 else 0  
user_input = input("Type what you want to add")
with open("user.txt","a+") as f:
    f.seek(0,0)
    lines = f.readlines()
with open("user.txt","w") as f:    
    f.writelines(lines[:projectnum]+ [user_input+'\n']+lines[projectnum:])