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("\\","")
Related
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)
I am trying to read the text within a .m file in Python and Python keeps reading a single character within the .m file as a line when I use file.readline(). I've also had issues with trying to remove certain parts of the line before adding it to a list.
I've tried adjusting where the readline is on for loops that I have set up since I have to read through multiple files in this program. No matter where I put it, the string always comes out separated by character. I'm new to Python so I'm trying my best to learn what to do.
# Example of what I did
with open('MyFile.m') as f:
for line in f:
text = f.readline()
if text.startswith('%'):
continue
else:
my_string = text.strip("=")
my_list.append(my_string)
This has only partially worked as it will still return parts of lines that I do not want and when trying to format the output by putting spaces between new lines it output like so:
Expected: "The String"
What happened: "T h e S t r i n g"
Without your input file I've had to make some guesses here
Input file:
%
The
%
String
%
Solution:
my_list = []
with open('MyFile.m') as f:
for line in f:
if not line.startswith('%'):
my_list.append(line.strip("=").strip())
print(' '.join(my_list))
The readLine() call was unnecessary as the for loop already gets you the line. The empty if was negated to only catch the part that you cared about. Without your actual input file I can't help with the '=' part. If you have any clarifications I'd be glad to help further.
As suggested by Xander, you shouldn't call readline since the for line in f does that for you.
my_list = []
with open('MyFile.m') as f:
for line in f:
line = line.strip() # lose the \n if you want to
if line.startswith('%'):
continue
else:
my_string = line.strip("=")
my_list.append(my_string)
I have three short JSON text files. I want to combine them with Python, and as far as it works and creates an output file with everything on the right place, on the last line I have a comma, and I would like to replace it with } . I have came up with such a code:
def join_json_file (file_name_list,output_file_name):
with open(output_file_name,"w") as file_out:
file_out.write('{')
for filename in file_name_list:
with open(filename) as infile:
file_out.write(infile.read()[1:-1] + ",")
with open(output_file_name,"r") as file_out:
lines = file_out.readlines()
print lines[-1]
lines[-1] = lines[-1].replace(",","")
but it doesn't replace the last line. Could somebody help me? I am new to Python and I can't find the solution by myself.
You are writing all of the files, and then loading it back in to change the last line. The change though will only be in memory, not in the file itself. The better approach would be to avoid writing the extra , in the first place. For example:
def join_json_file (file_name_list, output_file_name):
with open(output_file_name, "w") as file_out:
file_out.write('{')
for filename in file_name_list[:-1]:
with open(filename) as infile:
file_out.write(infile.read()[1:-1] + ",")
with open(file_name_list[-1]) as infile:
file_out.write(infile.read()[1:-1])
This first writes all but the last file with the extra comma, and then writes the last file seperately. You might also want to check for the case of a single file.
I am trying to extract file paths from a txt file. My file says C:\logs.
I use
with open(pathfile, "r") as f:
pathlist = f.readlines()
to produce a list with the path in, and then
path1 = str(pathlist)
to produce the line as a string. The list sees the line as it is in th efile, but te second command puts in an extra backslash: C:\logs.
I then do
os.chdir(path1)
to look at the path and I get the error
WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: "['C:\\logs']"
WHY is this? how can I prevent it?
I am looking to have many paths in the file and have the script search each path individually. Is this the best way to do it?
Thank you very much.
The extra backslash you see is an "escape" character, which is how the representation of the string disambiguates the existing backslash. It's not actually two backslashes
The problem is actually that pathlist is a list, and you're forcing it to be a str. Instead, take the first element of pathlist:
path1 = pathlist[0]
You may also have a line break at the end (another use of escape: \n or \r). To solve that, use .strip()
path1 = pathlist[0].strip()
str(pathlist) casts the list to a string, which results in ['C:\\logs'], which is definately not a valid path.
with open(pathfile, "r") as f:
for line in f:
# print the path (=line)
# strip() removes whitespace as well as the line break '\n' at the end
print(strip(line))
Or you could do:
for line in f:
print(line.replace('\\n', ''))
Or:
for line in f:
if line:
print(line.splitlines()[0])
Let's say the contents of pathfile are as follows:
C:\Path1
C:\Path2
C:\Path3
readlines returns a list of all lines in pathfile.
[ 'C:\Path1', 'C:\Path2', 'C:\Path3' ]
Using str on a python list creates a string which is a literal intrepretation of the list parseable by python. Its not what you want.
"[ \"C:\\Path1\", \"C:\\Path2\", \"C:\\Path3\" ]"
What you want is something like
import os
with open(pathfile, "r") as f:
for line in f.readlines():
path = line.strip() # strip newline characters from end of line
os.chdir(path)
I need to edit my file and save it so that I can use it for another program . First I need to put "," in between every word and add a word at the end of every line.
In order to put "," in between every word , I used this command
for line in open('myfile','r+') :
for word in line.split():
new = ",".join(map(str,word))
print new
I'm not too sure how to overwrite the original file or maybe create a new output file for the edited version . I tried something like this
with open('myfile','r+') as f:
for line in f:
for word in line.split():
new = ",".join(map(str,word))
f.write(new)
The output is not what i wanted (different from the print new) .
Second, I need to add a word at the end of every line. So, i tried this
source = open('myfile','r')
output = open('out','a')
output.write(source.read().replace("\n", "yes\n"))
The code to add new word works perfectly. But I was thinking there should be an easier way to open a file , do two editing in one go and save it. But I'm not too sure how. Ive spent a tremendous amount of time to figure out how to overwrite the file and it's about time I seek for help
Here you go:
source = open('myfile', 'r')
output = open('out','w')
output.write('yes\n'.join(','.join(line.split()) for line in source.read().split('\n')))
One-liner:
open('out', 'w').write('yes\n'.join(','.join(line.split() for line in open('myfile', 'r').read().split('\n')))
Or more legibly:
source = open('myfile', 'r')
processed_lines = []
for line in source:
line = ','.join(line.split()).replace('\n', 'yes\n')
processed_lines.append(line)
output = open('out', 'w')
output.write(''.join(processed_lines))
EDIT
Apparently I misread everything, lol.
#It looks like you are writing the word yes to all of the lines, then spliting
#each word into letters and listing those word's letters on their own line?
source = open('myfile','r')
output = open('out','w')
for line in source:
for word in line.split():
new = ",".join(word)
print >>output, new
print >>output, 'y,e,s'
How big is this file?
Maybe You could create a temporary list which would just contain everything from file you want to edit. Every element could represent one line.
Editing list of strings is pretty simple.
After Your changes you can just open Your file again with
writable = open('configuration', 'w')
and then put changed lines to file with
file.write(writable, currentLine + '\n')
.
Hope that helps - even a little bit. ;)
For the first problem, you could read all the lines in f before overwriting f, assuming f is opened in 'r+' mode. Append all the results into a string, then execute:
f.seek(0) # reset file pointer back to start of file
f.write(new) # new should contain all concatenated lines
f.truncate() # get rid of any extra stuff from the old file
f.close()
For the second problem, the solution is similar: Read the entire file, make your edits, call f.seek(0), write the contents, f.truncate() and f.close().