1

I have tried some codes myself based off of codes I found online but none seems to be working.

The text file contains something as such:

Student ID: 1230345

Course code:FHCT1024
Grade: A
GPA: 4.0000

CGPA :4.0000

and I want to delete the line with the string 'CGPA' in it. I tried using:

with open("file.txt", 'r') as inp, open("file.txt", 'w') as f:
    for line in inp:
        if line.strip().startswith("CGPA"):
            pass
        else:
            f.write(line)

But this deleted everything.

martineau
  • 119,623
  • 25
  • 170
  • 301
William
  • 13
  • 2
  • 1
    Opening a file in `'w'` mode destroys the existing contents. – John Gordon Dec 05 '20 at 16:23
  • You can't read and write to a file simultaneously (easily). Either write the results to a temporary file and rename it after deleting the original, or store the results in memory and rewrite the original file afterwards. – martineau Dec 05 '20 at 16:26

6 Answers6

1

You can filter the lines while you are reading the file

res = []

with open("file.txt", 'r') as inp:
            for line in inp:
                if line.strip().startswith("CGPA"):
                    pass
                else:
                    res += [line]

res will contain all the lines that do not start with "CGPA".

Once you have res , you can write it to a file if needed

Vaebhav
  • 4,672
  • 1
  • 13
  • 33
1
text='''Student ID: 1230345

Course code:FHCT1024
Grade: A
GPA: 4.0000

CGPA :4.0000'''

text_ls=text.splitlines()

for i in range(len(text_ls[:])):
    if text_ls[i].startswith('CGPA'):
        text_ls.remove(text_ls[i])
print('\n'.join(text_ls))
Dharman
  • 30,962
  • 25
  • 85
  • 135
Yash Makan
  • 706
  • 1
  • 5
  • 17
1

If the only purpose of your program is delete the line starting with CGPA, I would suggest you to look at sed command.

sed '/^CGPA/d' file.txt

This is much faster and needs lesser number of lines of code.

bigbounty
  • 16,526
  • 5
  • 37
  • 65
0

Let's open in append mode ('a'):

with open("file.txt", 'r') as inp, open("file.txt", 'a') as f:
            for line in inp:
                if line.strip().startswith("CGPA"):
                    pass
                else:
                    f.write(line)
Wasif
  • 14,755
  • 3
  • 14
  • 34
  • This appended the text without the CGPA line so if it was in write mode it would work i think thanks. – William Dec 06 '20 at 13:02
0

So the problem is that youre reading to the same file youre writing, this can lead to problems, because as youre reading the file the data is changing and is dynamic. Then you can try naming the file youre writing on differently. Here you have your input file named file.txt. Then name your output file "fileoutput.txt".

Also you can search for different opening file modes such as '+r' and others that can make this process easier.

But this should work:

with open("file.txt", 'r') as inp, open("fileoutput.txt", 'w') as f:
            for line in inp:
                if line.strip().startswith("CGPA"):
                    pass
                else:
                    f.write(line)
fluffykitten
  • 130
  • 8
0

If you need to read, update, then write; I would recommend breaking that up into two distinct open context managers: one for read and one for write because flat is easier to grok than nested. Also, you may want to write to a different file in order to preserve the original.

lines_without_cgpa = []

with open("file.txt", 'r') as f:
    for line in f.readlines():
        if "CGPA" not in line and "" != line:
            lines_without_cgpa.append(line)

print(lines_without_cgpa)

with open("file_without_cgpa.txt", 'w') as f:
    f.writelines(lines_without_cgpa)
aidanmelen
  • 6,194
  • 1
  • 23
  • 24