I'm trying to add new information, with several if loops, to a new file with append.() but I'm not sure that this works. The new file will also include some data from the f_file, that is why the if loops are there.

f=open('filename', 'r')
new=open('filename', 'w')
for data in f.readlines():
    if '#' not in data:
        new.append('notExist' + '\n')
    if 'SRM' in data:
        new.append(data + '\n')
    if '%' in data:
        new.append(data + '\n')

Is this correct? Do I need to add an 'a' instead of 'w' when opening the new file?

Edited 5 Years Ago by sofia85: n/a

File objects have no append() method. To add lines to a file, you must open it in append mode (mode 'a') and use the write() method. If you want to create a new file, it's the same code with mode 'w'.

f = open('filename', 'r')
new = open('other_filename', 'a')
for data in f: # f is iterable: no need for readlines()
    if '#' not in data:
    elif ('SRM' in data) or ('%' in data): # elif because a line may contain % and not #
        new.write(data) # data already contains \n

Edited 5 Years Ago by Gribouillis: n/a

This question has already been answered. Start a new discussion instead.