1

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()
6
  • 2
    what does Numberdata.dat look like? Is it just a bunch of lines, with one number per line? Commented Apr 10, 2012 at 15:17
  • Where does the code write to the file? Commented Apr 10, 2012 at 15:18
  • Numberdata is just a load of numbers all one line. Maybe that's where I'm going wrong? It is "444666444666444888111000444" Commented Apr 10, 2012 at 15:18
  • use NumberFile.write('1'), not print. Also you need to open file with 'w' permission, not 'r' Commented Apr 10, 2012 at 15:19
  • Changing the word 'line' to the word 'character' won't make Python start reading the file character by character. You need two nested loops - one to consume lines from the file, and one to consume characters from the lines. Commented Apr 10, 2012 at 15:28

7 Answers 7

2

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Sure thing. If you're going to be writing a bunch of python code I would recommend checking out pep8, most python programmers follow it, and your code looks positively weird to me. Also, the with statement (look at the examples, not the grammar) is preferred to raw open() and close() calls, for a variety of reasons.
2

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.

Comments

2

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.

Comments

0

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.

1 Comment

I think that if you write while reading Bad Things can happen? I've just avoided it on principle, though.
0

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)

Comments

0

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.

Comments

0

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 =)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.