Delete a specific line from txt file [duplicate] - python

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.

Related

How do you read the whole of a file in python as a single line instead of line by line? [duplicate]

This question already has answers here:
read the whole file at once
(2 answers)
Closed 7 months ago.
Let us say I wanted to read a whole file at once instead of going through it line by line (let's say for example to speed up retrieval of the times 'i' occurs in the file). How would I go about reading it as a whole instead of the lines in which it is written?
with open("file.ext", 'r') as f:
data = f.read()
As others have mentioned, you can find an official Python tutorial for Reading and Writing Files which explains this. You can also see the Methods of File Objects section, which explains the use of f.read(size) and f.readline() and the difference between between them.

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"))

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.

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

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?

How to effectively remove a line in the middle of a large file? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Fastest Way to Delete a Line from Large File in Python
How to edit a line in middle of txt file without overwriting everything?
I know I can read every line into a list, remove a line, then write the list back.
But the file is large, is there a way to remove a part in the middle of the file, and needn't rewrite the whole file?
I don't know if a way to change the file in place, even using low-level file system commands, but you don't need to load it into a list, so you can do this without a large memory footprint:
with open('input_file', 'r') as input_file:
with open('output_file', 'w') as output_file:
for line in input_file:
if should_delete(line):
pass
else:
output_file.write(line)
This assumes that the section you want to delete is a line in a text file, and that should_delete is a function which determines whether the line should be kept or deleted. It is easy to change this slightly to work with a binary file instead, or to use a counter instead of a function.
Edit: If you're dealing with a binary file, you know the exact position you want to remove, and its not too near the start of the file, you may be able to optimise it slightly with io.IOBase.truncate (see http://docs.python.org/2/library/io.html#io.IOBase). However, I would only suggest pursuing this if the a profiler indicates that you really need to optimise to this extent.

Categories