Issue
I am creating a Python program with which I need some assistance. The program I'm creating works as such.
The user inputs a raw binary input of 0's and 1's from a file. I then must be able to read this data in a particular manner. I want to read each line separately (180 binary digits long with multiple lines) and skip each line's first 30 binary numbers and the last 30 binary numbers. I will then store the collected data (of each line), missing the first and last 30 digits. This will be output to the user in a .txt file. I know how to read from a file and write a file, but I do not understand how to save or write the data I'm only interested in.
This is what I have so far so the user can input their file:
filename = input("What is the name of your file:")
fi = open(filename, "r")
This isn't much, but again, I lack the knowledge to interpret the data.
Here's an shortened example (ignoring the first and last 3 digits):
Let's say the file binary.txt contains the following:
000111000111000111
111000111000111000
Ran through my program, the output or newly saved file would contain:
111000111000
000111000111
I haven't found a way to interpret the binary data as I need to, so I have not tried any solutions. Turning each line of binary into a list may help determine the position of the data I want extracted. Would that be the right way to do it, and can that be achieved?
Solution
This code defines a function process_binary_line
. The process_binary_line
function checks whether each line is 180 characters long. If not, it raises a ValueError
, and the main
loop catches this error, prints an error message, and continues processing the next line.
The main
function handles reading the input file, processing each line, and writing the results to the output file.
Save this code to a Python file (e.g., process_binary.py
) and run it. It will prompt you for the input file, process the data as specified, and save the results to processed_output.txt
.
Here is the code; Please make the changes according to your needs.
def process_binary_line(line):
if len(line) == 180:
return line[30:-30]
else:
raise ValueError("Each line should be 180 characters long.")
def main():
filename = input("What is the name of your file: ")
try:
with open(filename, "r") as file:
lines = file.readlines()
processed_lines = []
for line_number, line in enumerate(lines, start=1):
try:
processed_line = process_binary_line(line.strip())
processed_lines.append(processed_line)
except ValueError as e:
print(f"Error in line {line_number}: {e}")
continue
output_filename = "processed_output.txt"
with open(output_filename, "w") as output_file:
for processed_line in processed_lines:
output_file.write(processed_line + "\n")
print(f"Processed data saved to {output_filename}")
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
if __name__ == "__main__":
main()
Answered By - Neeraj Roy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.