Charlie Bewsey
Charlie Bewsey

Reputation: 19

File Handling Permissions

So I am very new at file handling within python. I want to be able to read, write and append a text file all in one go. Here is what I think the code might look like:

name = input("Which file would you like to edit/view? \n --> ")
fhand = open((name), "r", "w", "a")
fhand.read()
fhand.write("Hello")
fhand.append("World")    
fhand.close()

However it returns this:

Traceback (most recent call last):
  File "\\godalming.ac.uk\dfs\UserAreas\Students\142659\test\filehandle tests.py", line 2, in <module>
fhand = open((name), "r", "w", "a")
TypeError: an integer is required (got type str)

Could you please advise on what is going wrong and how I could get around this?

Upvotes: 0

Views: 389

Answers (3)

tripleee
tripleee

Reputation: 189936

The open() function accepts two parameters (or three, but not relevant here), not a file name and a list of permissions. You seem to be looking for "r+".

The error message means that open tried to use "r" as a buffer size (that's the optional third argument) which needs to be an integer, obviously.

The fix is to replace "r", "a", "w" with "r+" so that the call to open() has exactly two arguments.

hand = open(name, "r+")

(The parentheses you had around name were superfluous, so I also took those out.)

Upvotes: 1

MutantOctopus
MutantOctopus

Reputation: 3581

The 'int' being sought is the integer for buffering. You've comma-delimited your 'mode' list, which is not the proper procedure; it reads "r" properly as the mode string, but when it reaches "w" it tries to take it in as the buffering int and spits back an error.

If you want to read and write, use "w+". To append to the end of the file, use f.seek(0, 2) before writing. To reset back to the start of the file, use f.seek(0, 0). And make sure to call f.close() before you end the program.

References: open method, file.seek method

Upvotes: 1

user4312749
user4312749

Reputation:

For read and write from / to a file I would recommend:

with open(filename, "r+") as f:
    data = f.read()
    f.seek(0)
    f.write(output)
    f.truncate()

Here's how you read a file, and then write to it (overwriting any existing data), without closing and reopening.

More, for all the options you can do:

with open(filename, "ra+") as f:
    ...

Upvotes: 0

Related Questions