How do I wrap a string in a file in Python?
For Python 2.x, use the StringIO module. For example:
>>> from cStringIO import StringIO
>>> f = StringIO('foo')
>>> f.read()
'foo'
I use cStringIO (which is faster), but note that it doesn't accept Unicode strings that cannot be encoded as plain ASCII strings. (You can switch to StringIO by changing "from cStringIO" to "from StringIO".)For Python 3.x, use the io
module.
f = io.StringIO('foo')
Treat a string as a file in python
You can create a temporary file and pass its name to open:
On Unix:
tp = tempfile.NamedTemporaryFile()
tp.write(b'there is a lot of blah blah blah in this so-called file')
tp.flush()
open(tp.name, 'r')
On Windows, you need to close the temporary file before it can be opened:tp = tempfile.NamedTemporaryFile(delete=False)
tp.write(b'there is a lot of blah blah blah in this so-called file')
tp.close()
open(tp.name, 'r')
You then become responsible for deleting the file once you're done using it. Wrap text in .txt file with Python3?
You can use textwrap.fill
that automatically places newlines for you and you can write it directly to file:
with open("test.txt", "w") as fiche:
fiche.write(my_wrap.fill(phrase))
and the content of test.txt will be:bla bla bla ceci est une phrase beaucoup
trop longue pour ce que je doit
réellement dire, en fait je peux même
dire qu'elle ne sert a rien, mais du
coup je doit quand même la tester
Replace \n with a text wrap with Python
you can also try this..
text = text.replace(r"\n", "\n")
add this line beforeoutputFile.write(text_to_write)
this line
The replace statement takes two parameters... : the first is the text you want to replace and the other is the replaced text you want to add...
you can also add the replace statement for []
and for ''
How to read a file and wrap the text at 80 characters?
Files are generally opened and referenced using a with
block, which handles closing the file handle automatically, even if an exception is raised.
You may also want to use textwrap.fill()
, which appends a newline to each processed paragraph.
import textwrap
with open('txt_file_name.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(textwrap.fill(line, width=80))
Python: create a file object from a string
There's io.StringIO
:
from io import StringIO
files.append(StringIO("Hello\n"))
A good way to make long strings wrap to newline?
You could use textwrap
module:
>>> import textwrap
>>> strs = "In my project, I have a bunch of strings that are read in from a file. Most of them, when printed in the command console, exceed 80 characters in length and wrap around, looking ugly."
>>> print(textwrap.fill(strs, 20))
In my project, I
have a bunch of
strings that are
read in from a file.
Most of them, when
printed in the
command console,
exceed 80 characters
in length and wrap
around, looking
ugly.
help on textwrap.fill
:>>> textwrap.fill?
Definition: textwrap.fill(text, width=70, **kwargs)
Docstring:
Fill a single paragraph of text, returning a new string.
Reformat the single paragraph in 'text' to fit in lines of no more
than 'width' columns, and return a new string containing the entire
wrapped paragraph. As with wrap(), tabs are expanded and other
whitespace characters converted to space. See TextWrapper class for
available keyword args to customize wrapping behaviour.
Use regex
if you don't want to merge a line into another line:import re
strs = """In my project, I have a bunch of strings that are.
Read in from a file.
Most of them, when printed in the command console, exceed 80.
Characters in length and wrap around, looking ugly."""
print('\n'.join(line.strip() for line in re.findall(r'.{1,40}(?:\s+|$)', strs)))
# Reading a single line at once:
for x in strs.splitlines():
print '\n'.join(line.strip() for line in re.findall(r'.{1,40}(?:\s+|$)', x))
output:In my project, I have a bunch of strings
that are.
Read in from a file.
Most of them, when printed in the
command console, exceed 80.
Characters in length and wrap around,
looking ugly.
How does one wrap text in kivy python file?
Try using \n
:
out = Label(text="Output: \nInput", font_size="25dp", color="#00FFCE")
or: text = '''
Abba
Dabba
Doo
'''
out = Label(text=text, font_size="25dp", color="#00FFCE")
Related Topics
Failed Loading English.Pickle with Nltk.Data.Load
Filtering a Pyspark Dataframe with SQL-Like in Clause
Plotting Results of Hierarchical Clustering Ontop of a Matrix of Data in Python
Change to Sudo User Within a Python Script
Running Multiple Bash Commands with Subprocess
Reading Tar File Contents Without Untarring It, in Python Script
Python Pandas Dataframe, Is It Pass-By-Value or Pass-By-Reference
What Does 'Wb' Mean in This Code, Using Python
Why Is the Apt-Get Function Not Working in the Terminal on MAC Os X V10.9 (Mavericks)
Start a Flask Application in Separate Thread
How to Change Tcp Keepalive Timer Using Python Script
Python Socket Receive - Incoming Packets Always Have a Different Size
Possible Values from Sys.Platform
How to Solve Equations in Python
Pyspark Dataframes - Way to Enumerate Without Converting to Pandas