Printing a txt file inside python shell - python

I have an assignment for class that has me transfer txt data from excel and execute in python. But every time I run it, only hex is displayed. I was wondering how to have the data displayed in ascii in the shell. This is the code I have so far. Is it possible to print it out in ascii in the shell?
infile = open("data.txt", 'r')
listName = [line.rstrip() for line in infile]
print (listName)
infile.close()

The reason its not working is because you are opening an Excel file - which is in a special format and is not a plain text file.
You can test this by yourself by opening the file in a text editor like Notepad; and you'll see the contents aren't in text.
To open the file and read its contents in Python you will need to do one of these two things:
Open the file in Excel, then save it as a text file (or a comma separated file CSV). Keep in mind if you do this, then you can only save one sheet at a time.
Use a module like pyexcel which will allow you to read the Excel file correctly in Python.
Just opening the file as plain text (or changing its extension) doesn't convert it.

Related

Reading and Typing in a new File IO

Why does the text not show up when I click on the file_io_reverse.ipynb file??
##I am trying to read 'file_io.ipynb' and put the reverse of it into 'file_io_reverse.ipynb', this code doesn't work at all
f = open('file_io_reverse.ipynb', "a")
with open('file_io.ipynb', "r") as f2:
for i in f2:
x = i[::-1]
print(x)
f.write(x)
f.close()
As #olvin pointed out, your mixture of ways of opening and closing files is inconsistent but not functionally incorrect and should work.
What are you trying to open the file_io_reverse.ipynb file in?
IPYNB notebooks are plain text files formatted using JSON, making them human-readable and easy to share with others. So if you are trying to reverse contents of each line in the file and trying to save it in another file, then that would make the new ipynb file invalid.
Try opening the file in a text editor, and it should have the reversed lines for each line in the file_io.ipynb.

Writing Python CSV files - encoding

I open a .csv file and I write another .csv file in output.
I specified encoding='utf-8' for both files.
When I read the input file, in a dictionary, I have an accented character (ì) which I can see in the variables I use, but "ì" becomes "ì" when I write it in the output file.
I create the output line by concatenating some variables, like this:
output_line = [name, address, citizenship_flag]
citizenship_flag may be "sì" or "no".
In the output file it becomes "ì".
Where am I wrong?
Thanks.

Python: Saving to CSV file, accidentally writing to next column instead of row after manually opening the file

I've noticed a really weird bug and didn't know if anyone else had seen this / knows how to stop it.
I'm writing to a CSV file using this:
def write_to_csv_file(self, object, string):
with open('data_model_1.csv', 'a') as f:
writer = csv.writer(f)
writer.writerow([object, string])
and then write to the file:
self.write_to_csv_file(self.result['outputLabel'], string)
If I open the CSV file to look at the results, the next time I write to the file, it will start in column 3 of the last line (column 1 is object, column 2 is string).
If I run self.write_to_csv_file(self.result['outputLabel'], string) multiple times without manually opening the file (obviously I open the file in the Python script), everything is fine.
It's only when I open the file so I get the issue of starting on Column 3.
Any thoughts on how to fix this?
You're opening the file in append mode, so the data is appended to the end of the file. If the file doesn't end in a newline, rows may get concatenated. Try writing a newline to the file before appending new rows:
with open("data_model_1.csv", "a") as f:
f.write("\n")

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")
Read the documentation of the open function (to open the file in write mode) and File 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 opening 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.
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

reading from multiple txt files - strip data and save to xls

i'm very new to python, so far i have written the following code below, which allows me to search for text files in a folder, then read all the lines from it, open an excel file and save the read lines in it. (Im still unsure whether this does it for all the text files one by one)
Having run this, i only see the file text data being read and saved into the excel file (first column). Or it could be that it is overwriting the the data from multiple text files into the same column until it finishes.
Could anyone point me in the right direction on how to get it to write the stripped data to the next available column in excel through each text file?
import os
import glob
list_of_files = glob.glob('./*.txt')
for fileName in list_of_files:
fin = open( fileName, "r" )
data_list = fin.readlines()
fin.close() # closes file
del data_list[0:17]
del data_list[1:27] # [*:*]
fout = open("stripD.xls", "w")
fout.writelines(data_list)
fout.flush()
fout.close()
Can be condensed in
import glob
list_of_files = glob.glob('./*.txt')
with open("stripD.xls", "w") as fout:
for fileName in list_of_files:
data_list = open( fileName, "r" ).readlines()
fout.write(data_list[17])
fout.writelines(data_list[44:])
Are you aware that writelines() doesn't introduce newlines ? readlines() keeps newlines during a reading, so there are newlines present in the elements of data_list written in the file by writelines() , but this latter doesn't introduce newlines itself
You may like to check this and for simple needs also csv.
These lines are "interesting":
del data_list[0:17]
del data_list[1:27] # [*:*]
You are deleting as many of the first 17 lines of your input file as exist, keeping the 18th (if it exists), deleting another 26 (if they exist), and keeping any following lines. This is a very unusual procedure, and is not mentioned at all in your description of what you are trying to do.
Secondly, you are writing the output lines (if any) from each to the same output file. At the end of the script, the output file will contain data from only the last input file. Don't change your code to use append mode ... opening and closing the same file all the time just to append records is very wasteful, and only justified if you have a real need to make sure that the data is flushed to disk in case of a power or other failure. Open your output file once, before you start reading files, and close it once when you have finished with all the input files.
Thirdly, any old arbitrary text file doesn't become an "excel file" just because you have named it "something.xls". You should write it with the csv module and name it "something.csv". If you want more control over how Excel will interpret it, write an xls file using xlwt.
Fourthly, you mention "column" several times, but as you have not given any details about how your input lines are to be split into "columns", it is rather difficult to guess what you mean by "next available column". It is even possible to suspect that you are confusing columns and rows ... assuming less than 43 lines in each input file, the 18th ROW of the last input file will be all you will see in the output file.

Categories