How to append new data onto a new line - python

My code looks like this:
def storescores():
hs = open("hst.txt","a")
hs.write(name)
hs.close()
so if I run it and enter "Ryan"
then run it again and enter "Bob"
the file hst.txt looks like
RyanBob
instead of
Ryan
Bob
How do I fix this?

If you want a newline, you have to write one explicitly. The usual way is like this:
hs.write(name + "\n")
This uses a backslash escape, \n, which Python converts to a newline character in string literals. It just concatenates your string, name, and that newline character into a bigger string, which gets written to the file.
It's also possible to use a multi-line string literal instead, which looks like this:
"""
"""
Or, you may want to use string formatting instead of concatenation:
hs.write("{}\n".format(name))
All of this is explained in the Input and Output chapter in the tutorial.

In Python >= 3.6 you can use new string literal feature:
with open('hst.txt', 'a') as fd:
fd.write(f'\n{name}')
Please notice using 'with statment' will automatically close the file when 'fd' runs out of scope

All answers seem to work fine. If you need to do this many times, be aware that writing
hs.write(name + "\n")
constructs a new string in memory and appends that to the file.
More efficient would be
hs.write(name)
hs.write("\n")
which does not create a new string, just appends to the file.

The answer is not to add a newline after writing your string. That may solve a different problem. What you are asking is how to add a newline before you start appending your string. If you want to add a newline, but only if one does not already exist, you need to find out first, by reading the file.
For example,
with open('hst.txt') as fobj:
text = fobj.read()
name = 'Bob'
with open('hst.txt', 'a') as fobj:
if not text.endswith('\n'):
fobj.write('\n')
fobj.write(name)
You might want to add the newline after name, or you may not, but in any case, it isn't the answer to your question.

I had the same issue. And I was able to solve it by using a formatter.
file_name = "abc.txt"
new_string = "I am a new string."
opened_file = open(file_name, 'a')
opened_file.write("%r\n" %new_string)
opened_file.close()
I hope this helps.

There is also one fact that you have to consider.
You should first check if your file is empty before adding anything to it. Because if your file is empty then I don't think you would like to add a blank new line in the beginning of the file. This code
first checks if the file is empty
If the file is empty then it will simply add your input text to the file else it will add a new line and then it will add your text to the file. You should use a try catch for os.path.getsize() to catch any exceptions.
Code:
import os
def storescores():
hs = open("hst.txt","a")
if(os.path.getsize("hst.txt") > 0):
hs.write("\n"+name)
else:
hs.write(name)
hs.close()

I presume that all you are wanting is simple string concatenation:
def storescores():
hs = open("hst.txt","a")
hs.write(name + " ")
hs.close()
Alternatively, change the " " to "\n" for a newline.

import subprocess
subprocess.check_output('echo "' + YOURTEXT + '" >> hello.txt',shell=True)

f=open("Python_Programs/files_forhndling.txt","a+")
inpt=str(input("Enter anything:\n>>"))
f.write(inpt)
f.write("\n")
print("Data inserted Successfully")
f.close()
welcome to file handling
new line
file handling in python
123456
78875454
✔ Output 💡 CLICK BELOW & SEE ✔

You need to change parameter "a" => "a+".
Follow this code bellows:
def storescores():
hs = open("hst.txt","a+")

Related

Writing string to file from loop if does not already exist

This has been asked and answered, and I've read lots of those posts... but for some reason my code isn't working. Hopefully someone can help.
The code matches strings within a variable and then attempts to write those strings to a file if they don't already exist within that file.
Code doesn't work. Any help please?
#this works
str_match = re.findall(r'(https?://[^\s]+)', input
if str_match:
with open (datestamp+_"strings.txt", "a+") as text_file:
for string in str_match:
#THIS DOES NOT WORK -- WITH OR WITHOUT THE '\n'
#WITH, ALWAYS SAYS IT EXISTS AND WRITES NOTHING
if (string + '\n') in text_file:
print "str exists"
else:
print "Doesn't exist"
text_file.write(string + '\n')
Without it, it says the string doesn't exist and writes it to the file multiple times.
if string in text_file:
print "str exists"
else:
print "Doesn't exist"
text_file.write(string + '\n')
If I look at the string that's written using vim, it looks like: mystring$
(the $ is appended at the end of each string -- and no, adding +"$" doesn't work)
Any help please?
The problem here is that files don't (really) support membership tests with the in operator.
The reason why no error is thrown is because files are iterable and thus x in file evaluates to any(x is e or x == e for e in file) (docs). This operation works only once, because after the first time the file has been exhausted and no more lines can be read (until you write new ones).
The solution to your problem is to read all the lines in the file into a list or set and use that for membership tests:
all_lines= set(text_file)
...
if (string + '\n') in all_lines:
However, this does not explain why if (string + '\n') in text_file: always returns True. In fact it should always (after the first iteration) return False, and that's exactly what happens when I run your code on my machine. There's probably something writing to the file in other parts of your code.
Problem is you are iterating through the file once, and file is not rewound afterwards. File is only scanned once.
You have to read the data into a set first, then you can loop over the strings (and set is very performant because uses dichotomic search in O(log(N)))
Problem: if there are duplicates in str_match, it will be written more than once, so I added unicity with a set
if str_match:
with open(datestamp+"_strings.txt", "r") as text_file: # read-only
lines = set(map(str.rstrip,text_file)) # reads the file, removes \n and \r
with open(datestamp+"_strings.txt", "a") as text_file: # append, write only
for string in set(str_match):
#THIS DOES NOT WORK -- WITH OR WITHOUT THE '\n'
#WITH, ALWAYS SAYS IT EXISTS AND WRITES NOTHING
if (string) in lines:
print("str exists")
else:
print("Doesn't exist")
text_file.write(string + '\n')
Notes:
to preserve the order in the file, remove set in the for string loop, and add the string to lines when found.
first version with \n added would work OK on Linux, but on windows it would fail because of the \r. Now I rstrip the lines when I put them in the mini-database: no need to add \n when testing and is portable
the string$ you saw in vim is explained: vim adds end-of-lines as $ when showing the text. Mystery solved.

Python: How to write a list of strings on separate lines but without a blank line

EDIT: See bottom of post for the entire code
I am new to this forum and I have an issue that I would be grateful for any help solving.
Situation and goal:
- I have a list of strings. Each string is one word, like this: ['WORD', 'LINKS', 'QUOTE' ...] and so on.
- I would like to write this list of words (strings) on separate lines in a new text file.
- One would think the way to do this would be by appending the '\n' to every item in the list, but when I do that, I get a blank line between every list item. WHY?
Please have a look at this simple function:
def write_new_file(input_list):
with open('TEKST\\TEKST_ny.txt', mode='wt') as output_file:
for linje in input_list:
output_file.write(linje + '\n')
This produces a file that looks like this:
WORD
LINKS
QUOTE
If I remove the '\n', then the file looks like this:
WORDLINKSQUOTE
Instead, the file should look like this:
WORD
LINKS
QUOTE
I am obviously doing something wrong, but after a lot of experimenting and reading around the web, I can't seem to get it right.
Any help would be deeply appreciated, thank you!
Response to link to thread about write() vs. writelines():
Writelines() doesn't fix this by itself, it produces the same result as write() without the '\n'. Unless I add a newline to every list item before passing it to the writelines(). But then we're back at the first option and the blank lines...
I tried to use one of the answers in the linked thread, using '\n'.join() and then write(), but I still get the blank lines.
It comes down to this: For some reason, I get two newlines for every '\n', no matter how I use it. I am .strip()'ing the list items of newline characters to be sure, and without the nl everything is just one massive block of texts anyway.
On using another editor: I tried open the txt-file in windows notepad and in notepad++. Any reason why these programs wouldn't display it correctly?
EDIT: This is the entire code. Sorry for the Norwegian naming. The purpose of the program is to read and clean up a text file and return the words first as a list and ultimately as a new file with each word on a new line. The text file is a list of Scrabble-words, so it's rather big (9 mb or something). PS: I don't advocate Scrabble-cheating, this is just a programming exercise :)
def renskriv(opprinnelig_ord):
nytt_ord = ''
for bokstav in opprinnelig_ord:
if bokstav.isupper() == True:
nytt_ord = nytt_ord + bokstav
return nytt_ord
def skriv_ny_fil(ny_liste):
with open('NSF\\NSF_ny.txt', 'w') as f:
for linje in ny_liste:
f.write(linje + '\n')
def behandle_kildefil():
innfil = open('NSF\\NSF_full.txt', 'r')
f = innfil.read()
kildeliste = f.split()
ny_liste = []
for item in kildeliste:
nytt_ord = renskriv(item)
nytt_ord = nytt_ord.strip('\n')
ny_liste.append(nytt_ord)
skriv_ny_fil(ny_liste)
innfil.close()
def main():
behandle_kildefil()
if __name__ == '__main__':
main()
I think there must be some '\n' among your lines, try to skip empty lines.
I suggest you this code.
def write_new_file(input_list):
with open('TEKST\\TEKST_ny.txt', 'w') as output_file:
for linje in input_list:
if not linje.startswith('\n'):
output_file.write(linje.strip() + '\n')
You've said in the comments that python is writing two carriage return ('\r') characters for each line feed ('\n') character you write. It's a bit bizaare that python is replacing each line feed with two carriage returns, but this is a feature of opening a file in text mode (normally the translation would be to something more useful). If instead you open your file in binary mode then this translation will not be done and the file should display as you wish in Notepad++. NB. Using binary mode may cause problems if you need characters outside the ASCII range -- ASCII is basically just latin letters (no accents), digits and a few symbols.
For python 2 try:
filename = "somefile.txt"
with open(filename, mode="wb") as outfile:
outfile.write("first line")
outfile.write("\n")
outfile.write("second line")
Python 3 will be a bit more tricky. For each string literal you wish you write you must prepend it with a b (for binary). For each string you don't have immediate access to, or don't wish to change to a binary string, then you must encode it using the encode() method on the string. eg.
filename = "somefile.txt"
with open(filename, mode="wb") as outfile:
outfile.write(b"first line")
outfile.write(b"\n")
some_text = "second line"
outfile.write(some_text.encode())

Python add character to string

I am trying to open a user's text file and replace a string in Python. I have the replacement working, but to open a file I understand that I need to add another backslash after each one in the file path. I am not sure how to do that. I looked at other stack overflow questions, but they were mostly about adding to the beginning or end of the string. Please help! Here's the code so far:
yourfile = input()
with open ("C:\\Users\\Rajrishi\\Documents\\MyJava\\text.txt") as myfile:
data = myfile.readlines()
strdata = "".join(data)
strdata = strdata.replace("a string","a replacement")
print(strdata)
You may find it easier to pass a raw string by prefixing with r
like so:
with open (r"C:\Users\Rajrishi\Documents\MyJava\text.txt") as myfile:
This will mean that you don't need to escape slashes
You can actually use forward slashes:
with open("C:/Users/Rajrishi/Documents/MyJava/text.txt") as myfile:
...
If your code and your file in the same folder, you can do this :
with open (r"text.txt") as myfile:
...
Just write name of the file.

how to add a new line in a text file using python without \n

I have a file that has a list of files but it adds \n at the end how can I have python just write the info I need on a new line without getting \n in the way so that way my info will be called X.acc not x.acc\n? Here is my code that writes the file
def add(x):
nl = "\n"
acc = ".acc"
xy = x + acc
exyz = xy
xyz = exyz
xxx = str(xyz)
tf = open('accounts.dat',"a+")
tf.writelines(nl)
tf.writelines(xxx)
tf.close
Here is the code that calls upon the file:
import sys
tf = open('accounts.dat','r')
names = tf.readlines()
u = choicebox(msg="pick something",title = "Choose an account",choices=(names))
counter_file = open(u, 'r+')
content_lines = []
for line in counter_file:
if line == "credits =":
creds = line
else:
False
for line in counter_file:
if 'credits =' in line:
line_components = line.split('=')
int_value = int(line_components[1]) + 1
line_components[1] = str(int_value)
updated_line= "=".join(line_components)
content_lines.append(updated_line)
else:
msgbox(msg=(creds))
content_lines.append(line)
counter_file.seek(0)
counter_file.truncate()
counter_file.writelines(content_lines)
counter_file.close()
thank you for your help and sorry if this is a trival question still new to python :)
Your question doesn't actually make sense, because of what a "line" actually is and what that '\n' character means.
Files don't have an intrinsic concept of lines. A file is just a sequence of bytes. '\n' is the line separator (as Python represents it with universal newlines). If you want your data to show up on different "lines", you must put a line separator between them. That's all that the '\n' character is. If you open up the file in a text editor after you write it, most editors won't explicitly show the newline character by default, because it's already represented by the separation of the lines.
To break down what your code is doing, let's look at the add method, and fix some things along the way.
The first thing add does is name a variable called nl and assign it the newline character. From this, I can surmise that nl stands for "newline", but it would be much better if that was actually the variable name.
Next, we name a variable called acc and assign it the '.acc' suffix, presumably to be used as a file extension or something.
Next, we make a variable called xy and assign it to x + acc. xy is now a string, though I have no idea of what it contains from the variable name. With some knowledge of what x is supposed to be or what these lines represent, perhaps I could rename xy to something more meaningful.
The next three lines create three new variables called exyz, xyz, and xxx, and point them all to the same string that xy references. There is no reason for any of these lines whatsoever, since their values aren't really used in a meaningful way.
Now, we open a file. Fine. Maybe tf stands for "the file"? "text file"? Again, renaming would make the code much more friendly.
Now, we call tf.writelines(nl). This writes the newline character ('\n') to the file. Since the writelines method is intended for writing a whole list of strings, not just a single character, it'll be cleaner if we change this call to tf.write(nl). I'd also change this to write the newline at the end, rather than the beginning, so the first time you write to the file it doesn't insert an empty line at the front.
Next, we call writelines again, with our data variable (xxx, but hopefully this has been renamed!). What this actually does is break the iterable xxx (a string) into its component characters, and then write each of those to the file. Better replace this with tf.write(xxx) as well.
Finally, we have tf.close, which is a reference to the close function of the file object. It's a no-op, because what you presumably meant was to close the file, by calling the method: tf.close(). We could also wrap the file up as a context manager, to make its use a little cleaner. Also, most of the variables aren't necessary: we can use string formatting to do most of the work in one step. All in all, your method could look like this at the end of the day:
def add(x):
with open('accounts.dat',"a+") as output_file:
output_file.write('{0}.acc\n'.format(x))
So you can see, the reason the '\n' appears at the end of every line is because you are writing it between each line. Furthermore, this is exactly what you have to do if you want the lines to appear as "lines" in a text editor. Without the newline character, everything would appear all smashed together (take out the '\n' in my add method above and see for yourself!).
The problem you described in the comment is happening because names is a direct reading of the file. Looking at the readlines documentation, it returns a list of the lines in the file, breaking at each newline. So to clean those names up, you want line 4 of the code you posted to call str.strip on the individual lines. You can do that like this:
names = tf.readlines()
for i in range(len(names)):
names[i] = names[i].strip() # remove all the outside whitespace, including \n
However, it's much cleaner, quicker, and generally nicer to take advantage of Python's list comprehensions, and the fact that file objects are already iterable line-by-line. So the expression below is equivalent to the previous one, but it looks far nicer:
names = [line.strip() for line in tf]
Just change add:
def add(x):
nl = "\n"
acc = ".acc"
xy = x + acc
exyz = xy
xyz = exyz
xxx = str(xyz)
tf = open('accounts.dat',"a+")
tf.writelines(xxx)
tf.writelines(nl) # Write the newline AFTER instead of before the output
tf.close() # close is a function so needs to be called by having () at the end.
See the comments for what has changed.
why dont you just write a function with "\n" at the end of the line.
So no need recall "\n" every time
I did this way-
import os
log_path = r"c:\python27\Logs\log.txt"
if not os.path.exists(r"c:\python27\Logs"):
os.mkdir(r"c:\python27\Logs")
def write_me_log(text):
global log_path
with open(log_path,"a+") as log:
log.write(text+"\n")
write_me_log("Hello this is the first log text with new line")
file = open("accountfile.txt","a")
file.write(username)
file.write(" ")
file.write(password)
file.write(" ")
file.write(age)
#need it to go down a line here so it writes"hello world" on the next line
file.write("hello world")
file.close()``

Delete newline / return carriage in file output

I have a wordlist that contains returns to separate each new letter. Is there a way to programatically delete each of these returns using file I/O in Python?
Edit: I know how to manipulate strings to delete returns. I want to physically edit the file so that those returns are deleted.
I'm looking for something like this:
wfile = open("wordlist.txt", "r+")
for line in wfile:
if len(line) == 0:
# note, the following is not real... this is what I'm aiming to achieve.
wfile.delete(line)
>>> string = "testing\n"
>>> string
'testing\n'
>>> string = string[:-1]
>>> string
'testing'
This basically says "chop off the last thing in the string" The : is the "slice" operator. It would be a good idea to read up on how it works as it is very useful.
EDIT
I just read your updated question. I think I understand now. You have a file, like this:
aqua:test$ cat wordlist.txt
Testing
This
Wordlist
With
Returns
Between
Lines
and you want to get rid of the empty lines. Instead of modifying the file while you're reading from it, create a new file that you can write the non-empty lines from the old file into, like so:
# script
rf = open("wordlist.txt")
wf = open("newwordlist.txt","w")
for line in rf:
newline = line.rstrip('\r\n')
wf.write(newline)
wf.write('\n') # remove to leave out line breaks
rf.close()
wf.close()
You should get:
aqua:test$ cat newwordlist.txt
Testing
This
Wordlist
With
Returns
Between
Lines
If you want something like
TestingThisWordlistWithReturnsBetweenLines
just comment out
wf.write('\n')
You can use a string's rstrip method to remove the newline characters from a string.
>>> 'something\n'.rstrip('\r\n')
>>> 'something'
The most efficient is to not specify a strip value
'\nsomething\n'.split() will strip all special characters and whitespace from the string
simply use, it solves the issue.
string.strip("\r\n")
Remove empty lines in the file:
#!/usr/bin/env python
import fileinput
for line in fileinput.input("wordlist.txt", inplace=True):
if line != '\n':
print line,
The file is moved to a backup file and standard output is directed to the input file.
'whatever\r\r\r\r\r\r\r\r\n\n\n\n\n'.translate(None, '\r\n')
returns
'whatever'
This is also a possible solution
file1 = open('myfile.txt','r')
conv_file = open("numfile.txt","w")
temp = file1.read().splitlines()
for element in temp:
conv_file.write(element)
file1.close()
conv_file.close()

Categories