There is no output from file.write [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I run the following program and expect to get the output in a .txt file.
I have run this in spyder IDE with python 3.6.
temperatures = [10,-20,-289,100]
file = open('temperature.txt','w')
def f_to_c(temperatures):
for celsius in temperatures:
if celsius > -273.15:
fahrenheit = celsius * (9/5) + 32
file.write(str(fahrenheit))
f_to_c(temperatures)
There is no error message in this code, but I didn't get the output in the .txt file. Can you help?

Updated function and explanation:
def f_to_c(file: str, temps: list):
with open(file, 'a', newline='\n') as f:
for temp in temps:
if temp > -273.15:
fahrenheit = temp * (9/5) + 32
f.write(f'{fahrenheit}\n')
temps = [10,-20,-289,100]
f_to_c('temperature.txt', temps)
Use with open, opens the file, only when the function is called.
The specific reason you never get any output in your file, is because file is never closed.
Using with, will automatically close the file. Reading and Writing Files
Opening the file inside the function, means you won't be looking to the outer scope, to find the file object. Scope of Variables in Python
Use a to append to the file, each time the function is called.
f'{fahrenheit}\n' is an f-string.
PEP 498 -- Literal String Interpolation
Using the f-string, there's no need to convert fahrenheit, using str()
(file: str, temps: list) uses PEP 484 - Type Hints
Alternatively:
Have a dedicated function for converting the temperatures.
This is the appropriate way do deal with the task.
Functions should do one thing.
Deal with the file separately
def f_to_c(temps: list) -> list:
return [temp * (9/5) + 32 for temp in temps if temp > -273.15]
temps = [10,-20,-289,100]
with open('temperature.txt', 'a', newline='\n') as f:
for value in f_to_c(temps):
f.write(f'{value}\n')
The function is implemented with List Comprehensions
The return statement

A cleaner approach below
def f_to_c(temperatures):
fahrenheit_results = []
for celsius in temperatures:
if celsius > -273.15:
fahrenheit_results.append(celsius * (9 / 5) + 32)
return fahrenheit_results
results = f_to_c([10, -20, -289, 100])
with open('out.txt','w') as out:
for r in results:
out.write(str(r) + '\n')

Related

AttributeError: 'str' object has no attribute 'write json [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
import json
print(f"Enter some numbers")
userWD = input("--->")
with open("./Users/" + "test" + ".json", "r") as userID:
tmp = json.load(userID)
tmpBalance = tmp['Balance']
with open("./Users/" + "test" + ".json", "w") as f:
newBalance = int(tmpBalance) - int(userWD)
json.dump(newBalance, tmpBalance)
When i run this code , im getting this error: AttributeError: 'str' object has no attribute 'write'
Can someone tell me what is wrong?
You're trying to dump to tmpBalance (which is a string):
json.dump(newBalance, tmpBalance)
You want to dump into the file:
json.dump(newBalance, f)
After you're done with the calculation, newBalance is just a number. If you want to retain the complete data structure {"Balance": 12345}, you need to assign the new balance value back tmp:
tmp['Balance'] = newBalance
and then write tmp to the file, instead of newBalance.
I would re-arrange things like so:
import json
account_file = "./Users/test.json"
with open(account_file, "r") as f:
account = json.load(f)
print(f"Your account balance: {account['Balance']}.")
wd_amount = input("How much do you want to withdraw? >")
account['Balance'] -= int(wd_amount)
with open(account_file, "w") as f:
json.dump(account, f)

ValueError when splitting lines in a text file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'd like to split each line of a text file into two by " - ", but I keep getting this error:
File "quiz.py", line 21, in Vocab
questions, answers = line.split("-")
ValueError: too many values to unpack (expected 2)
I'm quite new to coding and could use some help. All tips are welcome as well!
import hashlib
testFile = ""
def qSearch():
options = input ("Vocab/Grammar/or Special? (v/g/s)")
if options == "v":
testFile = "Vocabtest"
Vocab()
elif options == "g":
Grammar()
testFile = "Grammartest"
elif options == "s":
Special()
testFile = "Specialtest"
else:
qSearch()
def Vocab():
with open('Vocabtest.txt','r') as f:
for line in f:
questions, answers = line.split("-") ### error
print (questions)
qSearch()
The text in my text file is formatted like so:
Magandang umaga - Good Morning
Magandang hapon - Good Afternoon
Magandang gabi - Good evening
Magandang umaga sa’yo - Good Morning to you
Magandang hapon din sa’yo - Good Afternoon to you to
"Unpacking" is the name for what you're doing when you write
value1, value2 = a_list
When you do an assignment like that, you're implicitly making an assumption about how many values are contained in a_list -- here it's 2. If there's more or less than 2, there's no good way to give value1 and value2 values without doing very surprising and unhelpful things (like leaving one empty, or leaving some elements of the list unassigned).
So too many values to unpack means that there's at least one line in your file where line.split('-') results in more than 2 elements -- that is, there's at least one line with more than one -.
The problem is because on line 21 in your input text (.txt) file you have more than one - but you only expect one.
A safer way to do it would be to only split once:
questions, answers = line.split("-", 1)

I need to sum numbers in a file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Ok I'm learning read and write files at the moment but I need a little help to sum the numbers in a file.
def main ():
sample = open (r'C:\user\desktop\text.txt','r')
for i in range (the range of int is unknown)
file = sample.read ()
sample.close ()
main ()
You may iterate over the file like this:
for i in sample:
and convert using int() to an integer.
The for loop can be done with map and the sum with sum.
This is the final code:
def main ():
sample = open (r'C:\user\desktop\text.txt','r')
result = sum(map(int, sample))
print(result)
sample.close ()
main ()
What you want is:
for line in sample:
# process the line
If each line just contains an integer, you can simplify it further to sum(map(int, sample)).
To add safety, you should cast your integers with error checking and ensure that the file exists before reading it.
import os
def safecast(newtype, val, default=None):
try:
return newtype(val)
except ValueError:
pass
return default
def sumfile(filename):
if not os.path.isfile(filename):
return None
sum = 0
with open(filename, "r") as file:
for line in file:
sum += safecast(int, line, 0)
return sum
sum = sumfile(r'C:\user\desktop\text.txt')
print(sum)

Reading data from txt file only reads last line [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to print data from my text file into python
text_file = open ("Class1.txt", "r")
data = text_file.read().splitlines()
for li in data:
namelist = li.split(":")[0]
scorelist = li.split(":")[1]
print (namelist)
print (scorelist)
text_file.close()
My text file has:
Jim:13524
Harry:3
Jarrod:10
Jacob:0
Harold:5
Charlie:3
Jj:0
It only shows the last entry
Shell:
Would you like to view class 1, 2 or 3? 1
Jj
0
The problem is that you are over-writing the value of namelist and scorelist with each pass through the loop. You need to add each item to a list. Adding a sequential list of items to a list is usually done with list.append() or a list comprehension. Read the documentation, or do some tutorials?
To actually create list, you can do this:
namelist, scorelist = [],[]
for li in data:
namelist.append(li.split(":")[0])
scorelist.append(li.split(":")[1])
Alternately, this might be a better overall approach:
with open("Class1.txt", "r") as text_file:
names_scores = [(e[0],e[1]) for e in [li.split(":") for li in text_file]
for name,score in name_scores:
print(name,score)
This assumes you really just want to extract the names and scores and print them, not do anything else. How you handle and store the data depends a lot on what you are doing with it once you extract from the file.

Code not writing output to file [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
This code is not writing the output to the file. It only dumps the data in the .data file not the output which should be a range from 0 to 1.
import math
f = open('numeric.sm.data', 'r')
print f
maximum = 0
# get the maximum value
for input in f:
maximum = max(int(input), maximum)
f.close()
print('maximum ' + str(maximum))
# re-open the file to read in the values
f = open('numeric.sm.data', 'r')
print f
o = open('numeric_sm_results.txt', 'w')
print o
for input in f:
# method 1: Divide each value by max value
m1 = float(input) / (maximum)
o.write(input)
print repr(input.strip('\n')).rjust(5), repr(m1).rjust(5)
o.close()
f.close()
o.write(input)
should be
o.write(str(m1))
and probably you want to add a newline or something:
o.write('{0}\n'.format(m1))
It's because You have file handler called f
but it just points to an object, not the contents of your file
so,
f = open('numeric.sm.data', 'r')
f = f.readlines()
f.close()and then,
and then,
o = open('numeric_sm_results.txt', 'w')
for input in f:
# method 1: Divide each value by max value
m1 = float(input) / (maximum)
o.write(input) # Use casting if needed, This is File write
print repr(input.strip('\n')).rjust(5), repr(m1).rjust(5) # This is console write
o.close()

Categories