Print String to Text File

Print string to text file

It is strongly advised to use a context manager. As an advantage, it is made sure the file is always closed, no matter what:

with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s" % TotalAmount)

This is the explicit version (but always remember, the context manager version from above should be preferred):

text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()

If you're using Python2.6 or higher, it's preferred to use str.format()

with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: {0}".format(TotalAmount))

For python2.7 and higher you can use {} instead of {0}

In Python3, there is an optional file parameter to the print function

with open("Output.txt", "w") as text_file:
print("Purchase Amount: {}".format(TotalAmount), file=text_file)

Python3.6 introduced f-strings for another alternative

with open("Output.txt", "w") as text_file:
print(f"Purchase Amount: {TotalAmount}", file=text_file)

Python Saving long string in text file

it should work regardless of the string length

this is the code I made to show it:

import random

a = ''
number_of_characters = 1000000
for i in range(number_of_characters):
a += chr(random.randint(97, 122))
print(len(a)) # a is now 1000000 characters long string

textfile = open('textfile.txt', 'w')
textfile.write(a)
textfile.close()

you can put number_of_characters to whatever number you like but than you must wait for string to be randomized

and this is screenshot of textfile.txt: http://prntscr.com/bkyvs9

probably your problem is in string a.

Write a multi line string to a text file using Python

Try closing the file:

f = open("temporary.txt","w+")
f.write(mylongstring)
f.close()

If that doesn't work try using:

f = open("temporary.txt","w+")
f.writelines(mylongstring)
f.close()

If that still doesn't work use:

f = open("temporary.txt","w+")
f.writelines([i + '\n' for i in mylongstring])
f.close()

How to read a text file into a string variable and strip newlines?

You could use:

with open('data.txt', 'r') as file:
data = file.read().replace('\n', '')

Or if the file content is guaranteed to be one-line

with open('data.txt', 'r') as file:
data = file.read().rstrip()

How do I print specific strings from text files?

Since file_contents is the result of x.read(), it's a string not a list of strings.
So you're iterating on each character.

Do that instead:

file_contents = x.readlines()

now you can search in your lines

or if you're not planning to reuse file_contents, iterate on the file handle with:

for line in x:

so you don't have to readlines() and store all file in memory (if it's big, it can make a difference)

Print line above specific string from txt file

with open('dd.txt', 'r', encoding="utf-8") as f:
line = ''
for next_line in f:
if next_line.startswith('City'):
print(line)
line = next_line.strip()

EDIT:

with open('dd.txt') as f, open('out.txt', 'w') as f_out:
line = ''
for next_line in f:
if next_line.startswith('City'):
f_out.write(line)
line = next_line


Related Topics



Leave a reply



Submit