0

I am required to edit the file that's just created using copyFile().

However, readlines() always fails if the file is opened in either 'w' mode or 'w+' or in 'a' mode.

copyfile(fileObj.file_to_open, fileObj._copyToFileName)
    with open(fileObj._copyToFileName, 'w') as thisFile:
        lines = thisFile.readlines()

I am able to readlines() if I leave it to default mode (read mode).

Why would the open with write mode be a problem?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ilavarasan
  • 469
  • 4
  • 3
  • You are opening the file as ```write mode``` you need to open it as ```read mode``` , that means: ```with open(fileObj._copyToFileName, 'r') as thisFile:``` – EnriqueBet Apr 05 '20 at 22:14

2 Answers2

1

You're looking for the r+ or a+ mode, which allows read and write operations to files (see more).

With r+, the position is initially at the beginning, but reading it once will push it towards the end, allowing you to append. With a+, the position is initially at the end.

With f.seek(0) you can move the reading position to the beginning.

with open("filename", "r+") as f:
    text = f.read()    
    f.seek(0)
    # reread if required here
Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43
0

When you open a file in write mode, Python truncates the file. If you want to open the file for reading/writing without this, you need to use open(filename, 'r+').

Also make sure that you keep track of where in the file the cursor is located because you may overwrite your data. Use file.seek(offset) to control this.

Check the Python open documentation for more details.