0

Im trying to rewrite a file while its being used. I'm changing a line in a file which im reading ('students.txt') to a line which is similar the change would look like

Raymond_Red 0000000000000 0

to

Raymond_Red 0000000000000 1

The issue is is that i'm getting this error beacuse im opening a file which is already open using 'fileinput'

    PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'students.txt' -> 'students.txt.bak'

I have no idea how to get around this issue. Thanks in advance for your help!

 #Code by Byron Dalberg
    import time
    import fileinput
    lunch = str('inout {0}.txt'.format(time.strftime("%Y-%m-%d")))
    while True:
        variable = input()
        with open ('students.txt') as f:
            for eachline in f:
                name,inout,rfid = eachline.rsplit(None,2)
                if variable == rfid:
                    print("yay")
                    if(inout == 0):
                        f.close()
                        linein = str('{0} {1} {2}'.format(name,inout,rfid))
                        lineout = str('{0} 1 {1}'.format(name, rfid))
                        for line in fileinput.input('students.txt', inplace=1):
                            line.replace(linein, lineout),
                        with open('inout.txt','a+') as fp:
                            log = str('{0} loggged out at {1}(ID: {2})\n'.format(name,time.strftime("%H:%M"),rfid))
                            fp.write(log)
                    else:
                        linein = str('{0} {1} {2}'.format(name,inout,rfid))
                        lineout = str('{0} 0 {1}'.format(name, rfid))
                        for line in fileinput.input('students.txt', inplace=1):
                            line.replace(linein, lineout),
                        with open('inout.txt','a+') as fp:
                            log = str('{0} loggged in at {1}(ID: {2})\n'.format(name,time.strftime("%H:%M"),rfid))
                            fp.write(log)
                else:
                    print("nope")

Thanks in advance!

  • When another process is reading a file, it implements a write lock, hence you may not change the contents of file while others are reading it. However it is **Not** a good idea to update the data in this way. – ZdaR Oct 22 '17 at 06:47
  • 1
    post content of file. and the out put what you need. code looks messy. – not_python Oct 22 '17 at 07:01
  • 1
    why don't you load content of file all at once and process and write it back after processing it? writing into file frequently makes your code slow. – not_python Oct 22 '17 at 07:03
  • Why are you opening the same file so many times? You open it in the outer loop with `open ('students.txt') ` and then on each line of the file you try to open it again with `fileinput.input('students.txt', inplace=1)`. – PM 2Ring Oct 22 '17 at 07:13

0 Answers0