Kecoey
Kecoey

Reputation: 211

Cannot write to file

I'm trying to write each line of an existing file into two new files. Basically this will copy the file. The "oldMaster.write(line)" returns an error that says the file is not writable. I know my code is terrible. This is for a project and I'm really stuck.

file_str = input ("Enter a file name: ")

while True:
    try:
        file_obj = open(file_str, 'r')
        break
    except IOError:
        file_str = input("'Invalid file name' Enter a file name: ")        
prefix = input("Master File Prefix?")
old = prefix
old += ".old.txt"
new = prefix
new += ".new.txt"
oldMaster = open(old,"w")
newMaster = open(new,"w")

oldMaster = file_obj
newMaster = file_obj

for line_str in file_obj:
    line = line_str

    oldMaster.write(line)

Upvotes: 2

Views: 289

Answers (2)

nuT707
nuT707

Reputation: 1573

In your code, file_obj exists only into while. Try to print its value after while.

So then after you open file:

>>> oldMaster = open('\users.csv',"w")

look at what oldMaster equal to:

>>> oldMaster
<_io.TextIOWrapper name='\users.csv' mode='w' encoding='cp1251'>

then you ovewrite oldMaster with a variable file_obj, which has some values, but no file:

>>> oldMaster='smthelse'
>>> oldMaster
'smthelse'

So oldMaster contain smthelse, not file.

I think, you should delete while.

Upvotes: 0

user1786283
user1786283

Reputation:

You are not closing the file, you have to send the commit signal in order to write to the file.

Try using with, which opens and closes the file handle.

with open(old,"w") as oldMaster,open(new,"w") as newMaster:

Upvotes: 4

Related Questions