# F5_6 # open(fil, 'w'): Creates a file. Existing files with the same name will be erased # open(fil, 'r'): Open the file for reading. Throws and exception if the file doesn't exists. # open(fil, 'a'): Append (add) to existing file # open(fil, 'x'): Creates a new file. Throws and exception if the file exists. # Ex 1 filnamn = input('Name of file? ') # e.g. personer.txt fil = open(filnamn, 'r', encoding='utf-8') #utf-8 for åäö. print(fil.read()) # Reads the whole file, returns a string for rad in fil: print(rad, end='') # Gives two EOL without end='' fil.close() # Ex 2 filnamn = input('Name of file you want to create? ') fil_objekt = open(filnamn, 'w', encoding='utf-8') # Test 'a' for append print('Print a text, end with 0:') rad = input('Print a line:') while rad !='0': fil_objekt.write(rad+'\n') # OR print(rad,file=fil_objekt) rad = input('Print one more line, or 0:') fil_objekt.close() # cont. Ex 2 print('\nContent in file', filnamn) fil = open(filnamn, 'r', encoding='utf-8') for rad in fil: print(rad, end='') fil.close() print() print() # Ex 3 # readfile = 'personer.txt' # writefile = 'friends.txt' # with open(readfile, 'r') as f1, open(writefile, 'w') as f2: # Test 'x' # for person in f1: #Read a line from the file f1 refers to # if 'Niklas' in person: # continue # Skip Niklas # f2.write(person) # print('Content in file friends.txt') # # fil = open(writefile, 'r', encoding='utf-8') #Must open the file again # for rad in fil: # print(rad, end='') # fil.close()