Python - Outputting Variables to Txt File

How To Print Variable To A Text File In Python?

Use a to append, each time you open using w you overwrite, appending will append after any existing lines:

def do_this():
print url
text_file = open("Output.txt", "a")
text_file.write("Purchase Amount: %s\n" % url)

It would probably make more sense to just open once moving the logic into the function, something like:

def do_this(page):
with open("Output.txt", "a") as f:
while True:
url, n = getURL(page)
page = page[n:]
if not url:
break
f.write("Extracted URL : %s\n" % url)

I also added a \n to the write or all your data will be on a single line

How to print a variable in a txt file with Python 3

This will append your variables to the end of MyFile.txt, a txt file in the same directory as the python script.

# Open the text file
txt_file = open("MyFile.txt","a")

# Append new line
txt_file.write('\n')

# Append your variables
txt_file.write(xcookies + '\n')
txt_file.write(ycookies + '\n')

# Close file
txt_file.close()

Printing python variables to a txt file

I think this should work:

 f = open("Calculations.txt", "w")
f.write(str(div))
f.close

How can we write a text file from variable using python?

First of all, note that you are writing to the same file losing the old data, I don't know if you want to do that. Other than that, every time you write using those methods, you are overwriting the data you previously wrote to the output file. So, if you want to use these methods, you must write just 1 time (write all the data).

SOLUTIONS

Using method 1:

to_file = []

for line in open('resume1.txt'):
line = line.rstrip()
if line != '':
file = line
print(file)
to_file.append(file)

to_save = '\n'.join(to_file)

with open("resume1.txt", "w") as out_file:
out_file.write(to_save)

Using method 2:

to_file = []

for line in open('resume1.txt'):
line = line.rstrip()
if line != '':
file = line
print(file)
to_file.append(file)

to_save = '\n'.join(to_file)

print(to_save, file=open("resume1.txt", 'w'))

Using method 3:

import pathlib

to_file = []

for line in open('resume1.txt'):
line = line.rstrip()
if line != '':
file = line
print(file)
to_file.append(file)

to_save = '\n'.join(to_file)

pathlib.Path('resume1.txt').write_text(to_save)

In these 3 methods, I have used to_save = '\n'.join(to_file) because I'm assuming you want to separate each line of other with an EOL, but if I'm wrong, you can just use ''.join(to_file) if you want not space, or ' '.join(to_file) if you want all the lines in a single one.

Other method

You can do this by using other file, let's say 'output.txt'.

out_file = open('output.txt', 'w')

for line in open('resume1.txt'):
line = line.rstrip()
if line != '':
file = line
print(file)
out_file.write(file)
out_file.write('\n') # EOL

out_file.close()

Also, you can do this (I prefer this):

with open('output.txt', 'w') as out_file:
for line in open('resume1.txt'):
line = line.rstrip()
if line != '':
file = line
print(file)
out_file.write(file)
out_file.write('\n') # EOL

Extract the value of a variable from a text file

You can use str.partition() to extract the name and the value part separated by an "=". Then you can use str.strip() to remove the whitespaces.

variable = {}
with open('txt.toml', 'r') as file:
for line in file:
name, _, value = line.partition('=')
variable[name.strip()] = value.strip()

print(variable['base'])
$ python3 src.py 
14.0

This solution will work even if you have spaces in your source data and even if you have multiple equal "=" signs in your values

txt.toml

...
Scheme = "default value here = (12 == 12.0)"
...

code

...
print(variable['Scheme'])

output

$ python3 src.py 
"default value here = (12 == 12.0)"

Saving the int variable in the text file

If you want to rewrite the file, just close after read and write.

...
with open("totalbal.txt", "r+") as baltotal:
totalbal = int(baltotal.read())
baltotal.close
...
if event.type == MOUSEBUTTONDOWN:
totalbal += cps
with open("totalbal.txt", "w") as baltotal:
baltotal.write(str(totalbal))
baltotal.close
...

For clarity in your main process it's probably better to delegate the file write to a function. You should also consider how many times you actually want to write this information; mostly a game state wouldn't need to be recorded that often.



Related Topics



Leave a reply



Submit