python - adding a line to a txt file -


I'm trying to add a line at the end of a txt file. I'm reading some posts here and trying different options, but, for some reason, the new line has been added after the last one, it has just been added next to the last one.

So I was wondering what I am doing wrong ... Here I am showing my test:

Exam 1:

  #newprot In this case there is a new data entered by the user in 12345 for the line in the present = false F = open ('protocol.txt', 'a +'): if newProt == line: exists = True: f.write (newProt) f.close ()   

txt file after this code:

2sde45

21145

we34z12345

Test 2:

  exists = open ('protocol.txt', 'r +') Of F in the form f: in line f: if newProt == line: exists = true if it does not exist: F.write (newProt)   

after this code txt File: Just like the above ...

And, this way, I have tested some combinations to open the file, RB +, W etc. Letter to open, but for some reason I want to get the desired output textile file Not found:

2sde45

21344

we34z

12345

I do not know what I'm doing wrong, May include'm following here some examples of some other positions.

Try it:

  exists = false f = open ( 'Protocol .txt', 'a +') for the line in f: if newProt == line: exists = true if it does not exist: f.write ('\ n' + NewProt) f.close ()   

This adds a new line character at the end of the file and then adds a 'newprot'

edit: < p> Your code does not produce the desired result, so the reason is that you were typing the string in the file. New lines of text are not actually 'in' text files. Text file is literally a series of bytes called characters. Due different applications like text editors show you new lines, because it interprets some characters as formatting elements instead of letters or numbers.

'\ n' A formatting character (in the ASCII standard), and it tells your favorite text editor to start a new line. There are other people like '\ t' which creates a tab

See for more information

Comments

Popular posts from this blog

Java - Error: no suitable method found for add(int, java.lang.String) -

java - JPA TypedQuery: Parameter value element did not match expected type -

c++ - static template member variable has internal linkage but is not defined -