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.
Related
I am writing a list (simple[]) to a file using writelines() and I need each item from the list to be on a new line in the file. I am using the following code:
file_path_simple = r'[path_redacted]\tx_list_simple.txt'
with open(file_path_simple, 'w') as fp:
for i in simple:
#ignores any blank lines
if i == '':
continue
else:
fp.writelines([i])
fp.writelines('\n')
fp.close()
The problem I am having is that when read from the file later it includes the \n, so instead of python reading:
blablabla
it reads:
blablabla\n
How can I make it not read the \n? Or do I need to use something like re.split() to remove the \n prior to reading?
This seems like something really simple I am overlooking.
You can use rstrip.
i = i.rstrip('\n')
I am still learning python and have a question about the function readlines() The following is a part of my script:
f = open("demofile.txt", "r")
text = "".join(f.readlines())
print(text)
demofile.txt contains:
This is the first line
This is the second line
This is the third line
Now I want to add a single word to this so I get:
This is the first line
This is the second line
This is the third line
Example
I thought of something easy way of doing it:
f = open("demofile.txt", "r")
text = "".join(f.readlines())."Example"
print(text)
But that doesn't work (of course) I googled and looked around here but didn't really have the good keywords to search for this issue. Hopefully someone can point me in the right direction.
.readlines() returns list you can append() to it:
with open("demofile.txt") as txt:
lines = txt.readlines()
lines.append("Example")
text = "".join(lines)
print(text)
or you can unpack the file object txt, since its an iterator to a new list with the word you wanted to add:
with open("demofile.txt") as txt:
text = "".join([*txt, "Example"])
print(text)
Firstly, the open function in python opens a file in read mode by default. Thus, you do not need to specify the mode r when opening the file. Secondly, you should always close a file after you are done with it. A with statement in python handles this for you. Moreover, instead of using . to add Example onto the end of the string, you should use the concatenation operator in python to add a newline character, \n, and the string, Example.
with open("demofile.txt") as f:
text = "".join(f.readlines()) + "\nExample"
print(text)
This should help you. While dealing with files. It is always recommended to use with open('filename','r') as f instead of f=open('filename','r'). Using ContextManager during file open is the idea that this file will be open in any case whether everything is ok or any exception is raised. And you don't need to explicitly close the file i.e f.close().
end_text='Example'
with open('test.txt','r') as f:
text=''.join(f.readlines())+'\n'+end_text
print(text)
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+")
Okay, this may sound like a stupid question, but I can't solve this problem...
I need remove all instances of backslash from downloaded file... But,
output.replace("\","")
doesn't work. Python considers "\"," a string, rather than "\" one string and "" the other one.
How can I remove backslashes?
EDIT:
New problem...
Originally, downloaded file had to be processed, which I did using:
fn = "result_cache.txt"
f = open(fn)
output = []
for line in f:
if content in line:
output.append(line)
f.close()
f = open(fn, "w")
f.writelines(output)
f.close()
output=str(output)
#irrelevant stuff
with open("result_cache.txt", "wt") as out:
out.write(output.replace("\\n","\n"))
Which worked okay, reducing file's content to only one line...
And finally ended with having this contents only:
Line of text\
Another line of text\
There\\\'s more text here\
Last line of text
I can't use the same thing again, because it would transform every line to a value in a list, leaving brackets and commas... So, I need to have:
out.write(output.replace("\\n","\n"))
out.write(output.replace("\\",""))
in the same line... How? Or is there another way?
Just escape the backslash with a backslash:
output.replace("\\","")
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()