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"))
Related
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.
This question already has answers here:
Print string to text file
(8 answers)
Closed 1 year ago.
I'm looking for a way to get the output that I'm printing out here written in a .txt file
for y in list(permutations(sllist, 3)):
print("".join(y))
The Output in the console looks like that:
ccccaaaaaaaabbbbdddddddddd
ccccaaaaaaaabbbbeeeeeee
ccccaaaaaaaabbbbfff
ccccaaaaaaaabbbbgggggggggggg
ccccaaaaaaaabbbb2001
ccccaaaaaaaabbbb01
ccccaaaaaaaabbbb06
And that's exactly how I want to write it in the .txt file. Neatly arranged among each other.
Thanks in advance.
Use a context manager to open the file, so that it will be automatically and correctly closed, even if the code inside raises exceptions.
As pointed out in the comments, there is no need to create the whole list in memory, you can iterate over the object returned by permutations and each element will be produced as needed.
from itertools import permutations
sllist = "abcd"
with open("output.txt", "w") as f:
for y in permutations(sllist, 3):
line = "".join(y)
print(line)
f.write(f"{line}\n")
Cheers!
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.
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.
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?