Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
# Program to remove all the lines that contain the character `a' in a file and write it to another file.

What I have tried:

file=open('C:\\Users\\Admin\\OneDrive\\Documents\\sh.txt','r')
lines=file.readlines()
filen = open('C:\\Users\\Admin\\OneDrive\\Documents\\sh.txt','w')
files = open('sha.txt','w')
for i in lines:
    if 'a' in i:
        files.write(i)
    else:
        filen.write(i)
print(filen.read())
print(files.read())     
Posted
Updated 11-Jun-23 8:41am
Comments
Dave Kreskowiak 11-Jun-23 11:26am    
Did you want to post error messages you're getting, or should everyone just guess?
Richard MacCutchan 11-Jun-23 12:01pm    
At a (very rough) guess, the file you are trying to read is either empty, or does not exist.

Quote:
My program is not running

First of all make sure the problem, add checkpoints.
PHP
print("Program Started")
file=open('C:\\Users\\Admin\\OneDrive\\Documents\\sh.txt','r')
lines=file.readlines()
filen = open('C:\\Users\\Admin\\OneDrive\\Documents\\sh.txt','w')
files = open('sha.txt','w')
for i in lines:
    if 'a' in i:
        files.write(i)
    else:
        filen.write(i)
print(filen.read())
print(files.read())
print("Program Ended")
 
Share this answer
 
You're trying to write a file that you opened for reading: sh.txt; "file" (r) and "filen" (w).
 
Share this answer
 
When you open a file for reading, that establishes an non-exclusive lock on the file - which means that other people can also read it.
But ... opening a file for writing needs to establish an exclusive lock so that only one process can write to the file. If there are existing locks, the attempt to open the file will automatically fail as an exclusive lock cannot be established.

And if you have opened a file for writing, you can't read lines from it as it is created if it doesn't exist, or truncated to an empty file if it does - so your two reads at the bottom don't work either!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900