I’m trying to print a specific version number in a file. In this case, it should print '7.6.3.23091805'.
I know basic file management in Python, but I can’t seem to run through the string or list to do this.
Here’s the text file:
branch = u'fix'
nightly = False
official = True
version = u'7.6.3.23091805'
And here’s what I tried:
version_file = open("/version.py")
version_file_list = []
for line in version_file:
split_line = line.split("'")
version_file_list.extend(split_line)
version_file.close()
print(version_file_list)
I can’t seem to get past that, and I’m having trouble understanding string methods.
>Solution :
If you want to read the python file as a plain text file, you can do the following.
lines = []
with open("version.py", "r") as f:
lines = f.readlines()
for line in lines:
tokens = line.strip().split()
if tokens[0] == "version":
print(tokens[-1])
But, a better way to do this would be to simply import the variable from the python file.
from version import version
print(version)