How to get data out of a def function in python [duplicate]

2024/10/5 14:49:24

Trying to simplify lots of repetitive reading and writing in a script of mine, and I can not figure out how to get data out of def readfile.

def writefile(FILE, DATA):file = open(FILE, "w")X = str(DATA) file.write(X)file.close()def readfile(FILE):file = open(FILE, "r")readvar = file.read()file.close()readfile("BAL.txt")
print(readvar)

I would expect the value stored in BAL.txt to come back, but it always says that readvar is not defined. I just defined it in a function that I ran.

Error:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-f80fb5b2da05> in <module>14 15 readfile("test.txt")
---> 16 print(readvar)NameError: name 'readvar' is not defined
Answer
  • In Python, variables from inside a function are generally not accessible from the outside (Look up variable scoping).
  • You can put a return statement at the end of a function to return variables (readvar in this case) (and you almost always should).
  • Then you can assign the returned argument (readvar) to a new variable (e.g. rv).
  • You can also give it the same name.
  • Other Resources:
    • Python Scopes and Namespaces
    • Real Python: Defining Your Own Python Function
def writefile(FILE, DATA):file = open(FILE, "w")X = str(DATA) file.write(X)file.close()def readfile(FILE):file = open(FILE, "r")readvar = file.read()file.close()return readvarrv = readfile("BAL.txt")
print(rv)
https://en.xdnf.cn/q/119689.html

Related Q&A

Calculating RSI in Python

I am trying to calculate RSI on a dataframedf = pd.DataFrame({"Close": [100,101,102,103,104,105,106,105,103,102,103,104,103,105,106,107,108,106,105,107,109]})df["Change"] = df["…

Pandas groupwise percentage

How can I calculate a group-wise percentage in pandas?similar to Pandas: .groupby().size() and percentages or Pandas Very Simple Percent of total size from Group by I want to calculate the percentage…

How to deal with large json files (flattening it to tsv) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 3 years ago.Improve…

How can I find max number among numbers in this code?

class student(object):def student(self):self.name=input("enter name:")self.stno=int(input("enter stno:"))self.score=int(input("enter score:"))def dis(self):print("nam…

Assert data type of the values of a dict when they are in a list

How can I assert the values of my dict when they are in a list My_dict = {chr7: [127479365, 127480532], chr8: [127474697, 127475864], chr9: [127480532, 127481699]}The code to assert this assert all(isi…

Loading tiff images in fiftyone using ipynp

I am trying to load tiff images using fiftyone and python in ipynb notebook, but it just doesnt work. Anyone knows how to do it?

Regular expression to match the word but not the word inside other strings

I have a rich text like Sample text for testing:<a href="http://www.baidu.com" title="leoshi">leoshi</a>leoshi for details balala... Welcome to RegExr v2.1 by gskinner.c…

Make one image out of avatar and frame in Python with Pillow

If I haveandneed to getdef create_avatar(username):avatar, frame, avatar_id = get_avatar(username)if avatar is not None and frame is not None:try:image = Image.new("RGBA", size)image.putalpha…

Could not broadcast input array from shape (1285) into shape (1285, 5334)

Im trying to follow some example code provided in the documentation for np.linalg.svd in order to compare term and document similarities following an SVD on a TDM matrix. Heres what Ive got:results_t =…

Python URL Stepping Returns Only First Page Results

Any help with the below code would be appreciated. I have checked the results of h and g using print to verify that they are incrementing the url properly, but the program seems to be only repeating th…