| localhost8638/notebooks/Untitled27.ipynbkemel namespython3 Jupyter Untitled27
ID: 3725261 • Letter: #
Question
| localhost8638/notebooks/Untitled27.ipynbkemel namespython3 Jupyter Untitled27 Last Checkpoint 8 minutes ago (unsaved changes) le Edit View Insert Widgets Help File Edit Format View Help test a line 1 line 2 In [3]: def open_function(P): f open (P, r) first line f.readline rest - f.readlines () these are the files if r'aaa.txt if r' -"bbb.txt return first_line, a rest f.close rest a rest rest -b rest In [4]: a_rest-open_function(aa.txt') bbb - Notepad File Edit Format View Help test b line 1 line 2 h line 3 line 4 Traceback (most recent c last) NaneFrror python-input-4-d8eb85022996> in () --> 1 a_rest-open function(.aaa.txt.) python-input-3-4a36eb9b396b> in open-function(P) if r'bbb.txt: return first_line, a_rest f.close rest b rest -1e 12 NaneError: name'a rest' is not defined this functuon opens a file takes the top line of the file and calls it first_line and takes the rest of the file and calls it 'rest i would like to be able to differentiate between the 'rest' that can be extracted from the two files. so if rest came from aaa.txt i call rest a_ rest and if im loading it from bbb.txt i call it b_rest which i try to do with if 'raaa.txt: rest - a rest if 'r'bbb.txt: rest - b rest return first line, a rest however it doesnt work a rest-open function'aaa.txt') NameError Traceback (most recent call last) in nodule:0 -> 1 a rest-open function'aaa.txt') cipython-input-3-4a36eb9b396b> in open function(P) if rbbb.txt return first line, a rest f.close rest = b rest --10 12 how can i make this open_function work the way i want?Explanation / Answer
OPEN FUNCTION.PY
def open_function(p):
#opens the file in the argument 'p' & 'r' indicates: file in 'p' is for reading
f=open(p,'r')
first_line=f.readline()
rest=f.readlines()
# Compares the file name in argument 'p' and assigns the lines in rest to a_rest
if p =='aaa.txt':
a_rest = rest
#Returns the first line and rest of the lines in file
return first_line,a_rest
# Compares the file name in argument 'p' and assigns the lines in rest to b_rest
if p =='bbb.txt':
b_rest = rest
#Returns the first line and rest of the lines in file
return first_line,b_rest
f.close
# for opening desired text files
a_rest = open_function("aaa.txt")
b_rest = open_function("bbb.txt")
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.