简体   繁体   中英

Saving data into a text file

def ConvertFile():
  FileNameIn = 'Hexdata.dat'
  HexFile = open(FileNameIn, 'r')
  for Line in HexFile:
    print (Line)
    print (Binary(Line))
  HexFile.close()

So far I have that, which, when the program is run, converts the Hexidecimal number in the file to binary. This is in a file called Hexdata.dat

What I want to do is then save the binary output into a file called Binarydata.dat

How would I approach this in code? Be aware I'm new with Python and haven't covered this properly. I've tried different bits of code but they've all been unsuccessful, as really, they're all guesses.

I'm not asking you to solve the problem for me, but more asking how I would save the output of a program into a new text file.

You're already most of the way there. You already know how to open a file for reading:

HexFile = open(FileNameIn, 'r')

The 'r' there means "open for reading". If you look at the documentation for the open function , you will see that replacing the r with a w will open a file for writing:

OutputFile = open(FileNameOut, 'w')

And then you can send output to it like this:

print >>OutputFile, "Something to print"

Or use the write method on the file object:

OutputFile.write("Something to print\n")

You are currently opening the file in reading mode, so in order to write to the file, you would want to open the file with the buffering mode as ('w') . Quote from: http://docs.python.org . You can do so easily by replacing your 'r' with 'w' .

'w' for writing (truncating the file if it already exists

For more reference see open(name[, mode[, buffering]])

# the file name
FileNameIn = 'Hexdata.dat'

# create a file object: open it with "write" mode
HexFile = open(FileNameIn,"w")

for line in HexFile:
    HexFile.write(Binary(line))

HexFile.close()

Have you tried using open('Binarydata.dat', 'w') for writing to the file? There are plenty of ways to write to a file, most of which can be found here: http://docs.python.org/tutorial/inputoutput.html

Read the documentation of the open function (to open the file in write mode) andFile Objects (to write information to the opened file).

You have to have 2 files in this script. The one you're reading from and the one you're writing to. Use the option wb (write binary) when open ing the file you are going to write into. These two links should help a beginner with little or no Python knowledge complete your exercise: Intro to File Objects and Tutorial on File I/O .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM