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
return
statement at the end of a function to return variables (readvar
in this case) (and you almost always should).readvar
) to a new variable (e.g. rv
).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 readvar
rv = readfile("BAL.txt")
print(rv)
You're unable to see the value of readvar
because it's only locally defined within the scope of the readfile
function, not globally, as you're attempting to use it when calling print(readvar)
.
If you need a value to persist outside the scope of the function, you must return
it to where the function is called, like so:
def readfile(FILE):
file = open(FILE, "r")
file_data = file.read()
file.close()
return file_data
file_data = readfile("my_file.txt")
print(file_data)
I'd also suggest using a with
block when performing file operations. It's best practice as to ensure the file handle is correctly closed, even if exceptions occur. This improves the handling of any errors the operation may encounter. For example:
def writefile(FILE, DATA):
data = str(DATA)
with open(FILE, 'w') as write_stream:
write_stream.write(data)
def readfile(FILE):
with open(FILE, 'r') as read_stream:
file_data = read_stream.read()
return file_data
file_data = readfile("my_file.txt")
print(file_data)
If you wanted to access the file line-by-line, we simply include a for
loop within the scope of with
. For example, printing each line of the file:
def readfile(FILE):
with open(FILE, 'r') as read_stream:
for line in read_stream
print(line)
simple. try this one
def personal_data():
name1 = input("What is you 1st Name?").upper()
name2 = input("What is your last Name?").upper()
return name1 + name2
fname = personal_data()
print(fname)