Python replace a line only if it meets a condition [duplicate] - python

This question already has answers here:
How to search and replace text in a file?
(22 answers)
Closed 5 years ago.
I am trying to search through a jsp file, see if it contains a certain tag, and replace an attribute on the same line if the tag exists on the same line.
For example <c:out var="taskToRedirect" property="dueDate"
I am trying to see if the line contains <c:out and if it does, I need to change the "property" attribute to "value", and only on that line, I don't want to change all of the "property" attributes in the entire file.
Currently what I have is:
f = open(filepath)
c = f.read()
for i in c:
if ("<c:out" in i):
c=c.replace(i,i.replace("property","value"))
f.write(c)
f.close()
The code appears to do nothing, and throws no run time errors, c is the string representation of the contents of a file, and i is the current line in the file. Any suggestions are welcome.

I don't see where you write the output. The file doesn't change unless you write out those changes. c is only your internal copy.
Have you traced whether c changes as expected? Have you tried this with a small file?

Related

Python: create a file object from a string [duplicate]

This question already has answers here:
How do I wrap a string in a file in Python?
(4 answers)
Closed 9 months ago.
TLDR: How to create in Python a file object (preferably a io.TextIOWrapper, but anything with a readline() and a close() method would probably do) from a string ? I would like something like
f = textiowrapper_from_string("Hello\n")
s = f.readline()
f.close()
print(s)
to return "Hello".
Motivation: I have to modify an existing Python program as follows: the program stores a list (used as a stack) of file objects (more precisely, io.TextIOWrapper's) that it can "pop" from and then read line-by-line:
f = files[-1]
line = f.readline()
...
files.pop().close()
The change I need to do is that sometimes, I need to push into the stack a string, and I want to be able to keep the other parts of the program unchanged, that is, I would like to add a line like:
files.append(textiowrapper_from_string("Hello\n"))
Or maybe there is another method, allowing minimal changes on the existing program ?
There's io.StringIO:
from io import StringIO
files.append(StringIO("Hello\n"))

Why do i get an empty file when trying to edit it using pyhon? [duplicate]

This question already has answers here:
Difference between modes a, a+, w, w+, and r+ in built-in open function?
(9 answers)
Closed 1 year ago.
I am trying to edit a text file that is html using python. When printing it, it gives an empty file. Why it gets empty? I tried to print it because I don't know how to return it.
Here's the code:
import bleach
with open ('index1.txt','w') as f: #to open the file that contains html markups
bleach.clean(
'f',
tags=['p'],
attributes=['style'],
styles=['color'],
)
f=open('index1.txt')
content = f.read()
f.close()
print(content)
It becomes empty because you open file for writing with 'w' and thus make it empty as per documentation - just change it to 'r' or 'a'
It would remain empty because you're just creating a file & not writing anything on it.

Delete a specific line from txt file [duplicate]

This question already has answers here:
How to delete a specific line in a file?
(17 answers)
Closed 3 years ago.
So my problem is: I am working with Python on a Discord bot (using discord.py).
However, I want the bot to read a txt file, choose one line out of it and delete this line after that.
This is how far I've come:
list = open(r"C:\Users\Max\Documents\Python\Discord Bots\Test File\Text\text.txt","r+")
readlist = list.readlines()
text = random.choice(readlist)
for readlist in list: <-- I guess there is the problem
readlist = "\n" <-- here too
list.close()
You need to write the lines back to the file. Otherwise, you're just modifying the local variable. To do this with the same file object, you'll need to seek to the beginning of the file before you write. You'll probably also want to use a list of lines, e.g. from readlines, rather than iterating through the lines while you're writing them. You can then truncate any additional lines you didn't write over at the end.
For more information about reading and writing files and I/O, see https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files and https://docs.python.org/3/library/io.html.
Also, in your code, you're shadowing readlist and the built-in list.
This also has nothing to do with discord.py or Discord bots.

Using a text file as the input for a program [duplicate]

This question already has answers here:
How to read a text file into a string variable and strip newlines?
(27 answers)
Closed 4 years ago.
In a program, you can simulate a magic square by using a two-dimensional list. Write a Python program that tests whether or not a 3 by 3 grid is a valid magic square. The program reads the input from a text file named input.txt. Each line in the file contains exactly 9 numbers that correspond to the the second row, and the last three values correspond to the last row.
I am not struggling with how to create the program to check to see if the square is a magic square, but how do I read in the "input.txt" into the program when I run it?
If you're looking only for how to read the input.txt file, you can just do this:
f = open('input.txt', 'r'):
f.read()
Provided your input.txt file is in current path.

Python - how do I remove last two lines of file, append lines, then replace those two lines I removed? [duplicate]

This question already has answers here:
Search and replace a line in a file in Python
(13 answers)
How to modify a text file?
(8 answers)
how to replace (update) text in a file line by line
(3 answers)
Closed 5 years ago.
I am developing with Flask, and am trying to create a page to create pages (as a sort of custom CMS). So the page will need to create its own #app.route decorator for a function that renders the page template when called in the app.py file. What I have come up with is to create three functions: remove_last_two_lines and create_rendering_func and add_back_last_lines (named for what they do). The remove_last_two_lines function and the add_back_last_lines function do exactly what I want. What I'm having trouble with is the create_rendering_func. It simply doesn't do anything, and doesn't raise an error. So I think the code is valid (and I am passing valid arguments), I just don't understand why it isn't working. The lines being overwritten are empty (that's why there is multiple newlines after the last line of the function). Thanks in advance!
def add_new_url(route, func_name, title, filename):
lines = open(__file__, 'r').readlines()
lines[-6] = '#app.route(\'%s\')' % route
lines[-5] = '\ndef %s' % func_name
lines[-4] = '\n\trender_template(\'filename\', the_title=%s)\n\n\n\n\n' % title
(This method sucks. Any tips on better methods appreciated)
I would write the data to be inserted as a list of strings appended by newline characters (\n) and insert it into lines by slicing;
insert_lines = ["Hello\n", "World!\n"]
with open("my_text_file.txt") as myfile:
lines = myfile.readlines()
lines[-2:-2] = insert_lines
myfile.seek(0)
myfile.write(''.join(lines))
It necessitates reading the entire file into memory and creating a new file in memory before writing it, which could be a problem if your file is incredibly big, but it will insert "Hello" and "World!" before the second to last line of the file.

Categories