85 json.dump(data, jsonfile, indent=2)
86
87
88def main(file_name, arg): 89 # TSV -> CSV
90 if arg == "c":
91 print('Start converting ...')
59
60# TSV -> XML
61
62def convert2(file_name): 63
64 # PARSE XML
65 OrderedDict = collections.OrderedDict
31
32
33# TSV -> JSON
34def convert1(file_name): 35 OrderedDict = collections.OrderedDict
36
37 src = file_name + ".tsv"
19
20def convert(file_name):
21 # Open csv file
22 csv = io.open(file_name + ".csv", mode="w", encoding="utf-8") 23
24# Convert file_name.tsv to file_name.csv
25 with io.open(file_name + ".tsv", mode="r", encoding="windows-1252") as tsv:
17# TSV -> CSV
18
19
20def convert(file_name): 21 # Open csv file
22 csv = io.open(file_name + ".csv", mode="w", encoding="utf-8")
23
The local variable name hides the variable defined in the outer scope, making it inaccessible and might confuse.
filename = 'myfile.txt'
def read_file(filename): # This shadows the global `filename`
with open(filename) as file:
return file.readlines()
FILENAME = 'myfile.txt' # renamed global to UPPER_CASE as convention
def read_file(filename):
with open(filename) as file:
return file.readlines()
Another usual suspect of this is when you use the same parameter name inside a function as the global variable you are using. For example:
def run_app(app):
# This `app` shadows the global app...
app.run()
if __name__ == '__main__':
app = MyApp() # This is a global variable!
run_app(app)
To avoid this re-defining of a global, consider not defining app
as a global, but inside a main()
function instead:
def run_app(app):
# There is no longer a global `app` variable.
app.run()
def main():
app = MyApp()
run_app(app)
if __name__ == '__main__':
main()