Hi,
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')
f.close()
new.close()

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

Recommended Answers

All 2 Replies

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:
        new.write('notExist\n')
    elif ('SRM' in data) or ('%' in data): # elif because a line may contain % and not #
        new.write(data) # data already contains \n
f.close()
new.close()

thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.