Joe Barry
Joe Barry

Reputation: 37

Changing contents of a file - Python

So I have a program which runs. This is part of the code:

FileName = 'Numberdata.dat'
NumberFile = open(FileName, 'r')
for Line in NumberFile:
  if Line == '4':
    print('1')
  else:
    print('9')
NumberFile.close()

A pretty pointless thing to do, yes, but I'm just doing it to enhance my understanding. However, this code doesn't work. The file remains as it is and the 4's are not replaced by 1's and everything else isn't replaced by 9's, they merely stay the same. Where am I going wrong?

Numberdata.dat is "444666444666444888111000444"

It is now:

FileName = 'Binarydata.dat'
BinaryFile = open(FileName, 'w')
for character in BinaryFile:
  if charcter == '0':
    NumberFile.write('')
  else:
    NumberFile.write('@')
BinaryFile.close()

Upvotes: 1

Views: 1810

Answers (7)

Rik Poggi
Rik Poggi

Reputation: 29312

Because you need to write to the file as well.

with open(FileName, 'w') as f:
    f.write(...)

Right now you are just reading and manipulating the data, but you're not writing them back.

At the end you'll need to reopen your file in write mode and write to it.

If you're looking for references, take a look at theopen() documentation and at the Reading and Writing Files section of the Python Tutorial.

Edit: You shouldn't read and write at the same time from the same file. You could either, write to a temp file and at the end call shutil.move(), or load and manipulate your data and then re-open your original file in write mode and write them back.

Upvotes: 2

user1210049
user1210049

Reputation:

Because print doesn't write to your file. You have to open the file and read it, modify the string you obtain creating a new string, open again the file and write it again.

FileName = 'Numberdata.dat'
NumberFile = open(FileName, 'r')
data = NumberFile.read()
NumberFile.close()
dl = data.split('\n')
for i in range(len(dl)):
    if dl[i] =='4':
        dl[i] = '1'
    else:
        dl[i] = '9'
NumberFile = open(FileName, 'w')
NumberFile.write('\n'.join(dl))
NumberFile.close()

Try in this way. There are for sure different methods but this seems to be the most "linear" to me =)

Upvotes: 0

Li-aung Yip
Li-aung Yip

Reputation: 12486

A few things:

  • The r flag to open indicates read-only mode. This obviously won't let you write to the file.

  • print() outputs things to the screen. What you really want to do is output to the file. Have you read the Python File I/O tutorial?

  • for line in file_handle: loops through files one line at a time. Thus, if line == '4' will only be true if the line consists of a single character, 4, all on its own.

    If you want to loop over characters in a string, then do something like for character in line:.

  • Modifying bits of a file "in place" is a bit harder than you think.

    This is because if you insert data into the middle of a file, the rest of the data has to shuffle over to make room - this is really slow because everything after your insertion has to be rewritten.

    In theory, a one-byte for one-byte replacement can be done fast, but in general people don't want to replace byte-for-byte, so this is an advanced feature. (See seek().) The usual approach is to just write out a whole new file.

Upvotes: 0

quodlibetor
quodlibetor

Reputation: 8433

You need to build up a string and write it to the file.

FileName = 'Numberdata.dat'
NumberFileHandle = open(FileName, 'r')
newFileString = ""
for Line in NumberFileHandle:
  for char in line: # this will work for any number of lines.
      if char == '4':
        newFileString += "1"
      elif char == '\n':
        newFileString += char
      else:
        newFileString += "9"
NumberFileHandle.close()

NumberFileHandle = open(FileName, 'w')
NumberFileHandle.write(newFileString)
NumberFileHandle.close()

Upvotes: 2

DonCallisto
DonCallisto

Reputation: 29932

According to your comment:

Numberdata is just a load of numbers all one line. Maybe that's where I'm going wrong? It is "444666444666444888111000444"

I can tell you that the for cycle, iterate over lines and not over chars. There is a logic error.

Moreover, you have to write the file, as Rik Poggi said (just rember to open it in write mode)

Upvotes: 0

jamylak
jamylak

Reputation: 133724

You are not sending any output to the data, you are simply printing 1 and 9 to stdout which is usually the terminal or interpreter.

If you want to write to the file you have to use open again with w. eg.

out = open(FileName, 'w')

you can also use

print >>out, '1'

Then you can call out.write('1') for example.

Also it is a better idea to read the file first if you want to overwrite and write after.

Upvotes: 0

kindall
kindall

Reputation: 184375

First, Line will never equal 4 because each line read from the file includes the newline character at the end. Try if Line.strip() == '4'. This will remove all white space from the beginning and end of the line.

Edit: I just saw your edit... naturally, if you have all your numbers on one line, the line will never equal 4. You probably want to read the file a character at a time, not a line at a time.

Second, you're not writing to any file, so naturally the file won't be getting changed. You will run into difficulty changing a file as you read it (since you have to figure out how to back up to the same place you just read from), so the usual practice is to read from one file and write to a different one.

Upvotes: 2

Related Questions