I read a text file which contains numbers as columns without spaces between them as
mediaXoriginal = open('posx_mean_no_acoplo_tf_multiple.txt', 'r')
and I plot my results as
print(mediaXoriginal.read())
However, I need mediaXoriginal to be a float, since I want to interpolate the data inside. If I write
float(mediaXoriginal)
I get the following error.
float() argument must be a string or a number, not '_io.TextIOWrapper'
Can someone tell me how to convert mediaXoriginal to float?
In the end I managed to do it as
with open('posx_mean_no_acoplo_tf_multiple.txt', 'r') as f2:
data = f2.read()
print(data)
Related
How can I read a column from a CSV file and turn all of it into a string, and then add it?
import csv
print("HI!, Welcome to spreadsheet reader protype")
fileNameLocator = input("Search file: ") + ".csv"
fileName = open(fileNameLocator)
fileReader = csv.reader(fileName)
# price column
next(fileReader)
for line in fileReader:
print(line[11])
I have this block of code that prints the desired columns I want from a file, and it gives the numbers vertically as a list, but these numbers are a string, how can I turn them into floats (they are decimals) and then add this numbers(20 or so).
In Python, to cast something as a float, you pass it into the float constructor.
Example:
number_string = '1.234'
print(type(number_string))
number = float(number_string)
print(type(number))
In your case, it would be something like number = float(line[11]).
I have a number of text files with a single long hex number inside each file. I want to find out the length of each hex number, i.e. ['FFFF0F'] =6, ['A23000000000000FD'] =17.
i read the file in:
file_to_open = open(myFile , 'r')
filey = file_to_open.readlines()
print(type(filey))
a = hex(int(filey, 16))
print(type(a))
n = len(filey)
print('length = ', n)
And my error is:
TypeError: int() cannot convert non-string with explicit base
if I remove the base 16 I get the error:
TypeError : int() argument must be a string, a bytes-like object or a number, not 'list'
Any ideas on how to just read in the number and find how many hex digits it contains?
readlines returns list of strs (lines) - in case of one-line file it is list with one element. Use read to get whole text as single str, strip leading and trailing whitespaces, then just get len:
with open(myFile , 'r') as f:
filey = f.read()
filey = filey.strip()
n = len(filey)
Note also that I used with so I do not have to care about closing that file handle myself. I assume all your files are single-line and contain some hex number. Note that if your number has any leading 0s, they will be counted too, so for example length of 000F is 4.
this is my simple code:
I have tried changing some datatype
#staticmethod
def load_from_file(filename, size_fit = 50):
'''
Loads the signal data from a file.
filename: indicates the path of the file.
size_fit: is the final number of sample axes will have.
It uses linear interpolation to increase or decrease
the number of samples.
'''
#Load the signal data from the file as a list
#It skips the first and the last line and converts each number into an int
data_raw = list(map(lambda x: int(x), i.split(" ")[1:-1]) for i in open(filename))
#Convert the data into floats
data = np.array(data_raw).astype(float)
#Standardize the data by scaling it
data_norm = scale(data)
and it throwing an error as:
data=np.array(data_raw).astype(float)
float() argument must be 'string' or 'number', not 'map'
please help me resolve this issue
You are making a list of map objects. Try this list comprehension instead:
data_raw = [[int(x) for x in i.split()[1:-1]] for i in open(filename)]
split defaults to splitting on whitespace, so the argument is unnecessary. Also, consider using with to properly close your file:
with open(filename) as infile:
data_raw = [[int(x) for x in i.split()[1:-1]] for i in infile]
On a side note, numpy converts strings to numbers for you when you do astype, so you could simply do
with open(filename) as infile:
data_raw = [i.split()[1:-1] for i in infile]
I normally use txt files but i need to use a csv i based this off how i do txt files and i am not sure what i am doing wrong can anyone help me please.
Home = "Road"
House = 5
def Save(Home,House):
Saved=open('Saved.csv', 'a')
Saved.write(Home+House+"/n")
Saved.close()
Save(Home,House)
I get this error
File "F:/Pygame/Test12.py", line 74, in Save
Saved.write(Home+House+"/n")
TypeError: cannot concatenate 'str' and 'int' objects
1) that's not a .csv file.
2) in python, you cannot concatenate integers with strings without prior conversion.
3) doing this: Home+str(House) would be legal, but when you want to read back your file you have to separate both fields (you provided no way of separating them)
Here's a code which would create a real csv file:
import csv
def Save(Home,House):
with open('Saved.csv', 'a') as Saved:
cw = csv.writer(Saved)
cw.writerow([Home,House])
when you compose your row, you can put any data you want, the csv module will convert it to string if needed.
BTW to read it back, use a csv.reader and iterate through the rows. Since you know the datatype, you can convert 2nd column to int directly.
with open('Saved.csv', 'r') as Saved:
cr = csv.reader(Saved)
for row in cr:
Home = row[0]
House = int(row[1])
# now you have to do something with those variables :)
You can not concatenate an integer with a string, use the following to convert the int to string:
Saved.write(Home + str(House) + "\n")
Python variables have types. So you are trying to add 5 to the 'House' which is not defined application. To make this work you have to convert number 5 to string '5'. As ettanany suggest use
Saved.write(Home+str(House)+"\n")
Also, note that it's '\n' not '/n'
I'm pretty new to python, using python 2.7. I have to read in a binary file, and then concatenate some of the bytes together. So I tried
f = open("filename", "rb")
j=0
infile = []
try:
byte = f.read(1)
while byte != "":
infile.append(byte)
byte = f.read(1)
finally:
f.close()
blerg = (bin(infile[8])<<8 | bin(infile[9]))
print type
where I realize that the recast as binary is probably unnecessary, but this is one of my later attempts.
The error I'm getting is TypeError: 'str' object cannot be interpreted as index.
This is news to me, since I'm not using a string anywhere. What the !##% am I doing wrong?
EDIT: Full traceback
file binaryExtractor.py, line 25, in
blerg = (bin(infile[8])<<8 | bin(infile[9]))
TypeError: 'str' object cannot be interpreted as index
You should be using struct whenever possible instead of writing your own code for this.
>>> struct.unpack('<H', '\x12\x34')
(13330,)
You want to use the ord function which returns an integer from a single character string, not bin which returns a string representation of a binary number.