I am trying to write the date to a .txt file. The following is the code that I have made to do this but it always gives me an error.
import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist[0]
file = open('Date.txt', 'a')
file.write(mylist)
file.close()
This code gives me the following error:
Traceback (most recent call last): File "/Volumes/CHROME
USB/STORAGE/Date.py", line 9, in
file.write(mylist) TypeError: argument 1 must be string or read-only character buffer, not list
Will someone please give me an example of a working code?
You can only write strings, it is stated in the error.
So you can do this to write the liste (converted in string) into the txt file:
file.write(str(mylist))
Simple example
>>> a= [1,2,3]
>>> b = str(a)
>>> b
'[1, 2, 3]'
>>> f = open("data","w")
>>> f.write(b)
>>> f.close()
>>>
$ cat data
[1, 2, 3]
File#write expects a string, not a list. Try file.write(repr(mylist)).
If you want to write the contents of the list, do it like this:
for entry in mylist:
file.write(str(entry))
or
map(lambda x: file.write(str(x)), mylist)
Related
I would like to extract the 5:
my_list = [[123],[456],[789]]
print(my_list[1][1])
error message:
Traceback (most recent call last):
File "C:\Users\IK\PycharmProjects\WithoutUSB\Udemy course 1\more than 1 dimension.py", line 4, in <module>
f()
File "C:\Users\IK\PycharmProjects\WithoutUSB\Udemy course 1\more than 1 dimension.py", line 3, in f
return(my_list[1][1])
IndexError: list index out of range
You cannot directly access a position in an integer, you need to convert is to string first:
my_list = [[123],[456],[789]]
print(str(my_list[1][0])[1])
output: 5
Breakdown:
>>> my_list[1]
[456]
>>> my_list[1][0]
456
>>> str(my_list[1][0])
'456'
>>> str(my_list[1][0])
'5'
you also define like this
my_list = [[1,2,3],[4,5,6],[7,8,9]]
print(my_list[1][1])
I have a list with 1550500 numbers, and all of them with quotes.
Example: list('100', '150', '200', '250') etc...
I need to sum all the numbers, but before that I need to convert it to INT.
List Name: trip_list
My code:
mean_tripstr = str(trip_list)
mean_trip = [int(x) for x in mean_tripstr]
print(type(mean_trip))
Error message:
Traceback (most recent call last):
File "projeto1.py", line 235, in <module>
mean_trip = [int(x) for x in mean_tripstr]
File "projeto1.py", line 235, in <listcomp>
mean_trip = [int(x) for x in mean_tripstr]
ValueError: invalid literal for int() with base 10: '['
What am I doing wrong? I am new to coding...
Python has a map function, this takes a function and an iterable. There is also the sum function, which returns the sum of an iterable.
You can use this:
sum(map(int(trip_list))
Note that the map function does not return a list, it returns a generator. To convert it to a list, use
list(sum(map(int, trip_list)))
(this may take a while as it requires iterating over the entire list, and yours is quite long).
The error with your code is converting your list to a string, that is,
>>> my_list = ["5", "6"]
>>> my_list_str = str(my_list)
>>> my_list_str
"['5', '6']"
>>> type(my_list_str)
<class 'str'>
>>> type(my_list)
<class 'list'>
So when you try to iterate over the string, the first x is [ which is not a number (thus the exception).
As a sidenote, using list(map(int, a_list)) is faster than [int(i) for i in a_list]
>>> c1 = "list(map(int, a_list))"
>>> c2 = "[int(i) for i in a_list]"
>>> s = "a_list = [str(i) for i in range(1000)]"
>>> import timeit
>>> timeit.timeit(c1, setup=s, number=10000)
1.9165708439999918
>>> >>> timeit.timeit(c2, setup=s, number=10000)
2.470973639999997
You have to convert each element to int:
mean_tripstr = map(str,trip_list)
mean_trip = list(map(int,mean_tripstr))
The code above uses a generator, what is more efficient in cases when you just have to iterate in a list. The last line convert to a list again properly.
But, as you said, if you already have a list of strings, you can just do:
mean_trip = list(map(int,trip_list))
If you know numpy, you can do too:
import numpy as np
trip_list = np.array(trip_list)
mean_trip = trip_list.astype(np.int)
I have the following list (the actual file is much larger and complex)
a = [[['3x5'], ['ff']], [['4x10'], ['gg']]]
I would like to use the split functionality for the first element in the list and get the value in which appears after "x". The final results should be 5 and 10 in this case. I tried to use split in this format
for line in a:
print str(line[0]).split("x")[1]
but the output is
5']
10']
I know I can easily manipulate the output to get 5 and 10 but what is the correct way of using split in this case?
And I am interested in using split for specific element of a list (first elements in this case).
You need to dive one level deeper, and dont use str() on the list.
>>> a = [[['3x5'], ['ff']], [['4x10'], ['gg']]]
>>> for y in a:
... if 'x' in y[0][0]:
... print y[0][0].split('x')[-1]
5
10
You shouldn't the list to a string object, however, you can do it use:
>>> [i[0][0].split('x')[1] for i in a]
['5', '10']
I think you also want to convert the output to int object, then you can simply add an int() like below:
>>> [int(i[0][0].split('x')[1]) for i in a]
[5, 10]
However, if you don't need save the output into a list, but print it out instead, you can just use the same code, but write another version:
a = [[['3x5'], ['ff']], [['4x10'], ['gg']]]
for i in a:
print(i[0][0].split('x')[1])
Output:
5
10
Remember that my code will failed (raise IndexError: list index out of range) when a is... For example [[['3x5'], ['ff']], [['kk'], ['gg']]] (the first element in one of the sublists isn't in format like '3x5').
However, a simple if can fix this:
>>> a = [[['3x5'], ['ff']], [['kk'], ['gg']]]
>>> [int(i[0][0].split('x')[1]) for i in a]
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 1, in <listcomp>
IndexError: list index out of range
>>> [int(i[0][0].split('x')[1]) for i in a if 'x' in i[0][0]]
[5]
Or even better, use RegEx to check, which can avoid something like a = [[['3x5'], ['ff']], [['xxxxxxx'], ['gg']]]:
>>> import re
>>> a = [[['3x5'], ['ff']], [['xxxxxxx'], ['gg']]]
>>> [int(i[0][0].split('x')[1]) for i in a if re.search(r'\d+x\d+', i[0][0])]
[5]
Another way, if you don't want import re:
>>> [int(i[0][0].split('x')[1]) for i in a
... if all(j.isdigit() for j in i[0][0].split('x'))]
[5]
I'm using readlines method from python to get list of all data lines. Now I wan't to access some index from that list:
file = open('article.txt', 'r')
data = file.readlines()
print data.index(1)
Error: data isn't a list
What's wrong?
I think you mean (if your goal is to print the second element of the list):
print data[1]
data.index(value) returns the list position of value:
>>> data = ["a","b","c"]
>>> data[1] # Which is the second element of data?
b
>>> data.index("a") # Which is the position of the element "a"?
0
>>> data.index("d") # Which is the position of the element "d"? --> not in list!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.index(x): x not in list
Sounds like you mean print data[1] not print data.index(1). See the tutorial
In Python 2, file objects had an xreadlines() method which returned an iterator that would read the file one line at a time. In Python 3, the xreadlines() method no longer exists, and realines() still returns a list (not an iterator). Does Python 3 has something similar to xreadlines()?
I know I can do
for line in f:
instead of
for line in f.xreadlines():
But I would also like to use xreadlines() without a for loop:
print(f.xreadlines()[7]) #read lines 0 to 7 and prints line 7
The file object itself is already an iterable.
>>> f = open('1.txt')
>>> f
<_io.TextIOWrapper name='1.txt' encoding='UTF-8'>
>>> next(f)
'1,B,-0.0522642316338,0.997268450092\n'
>>> next(f)
'2,B,-0.081127897359,2.05114559572\n'
Use itertools.islice to get an arbitrary element from an iterable.
>>> f.seek(0)
0
>>> next(islice(f, 7, None))
'8,A,-0.0518101108474,12.094341554\n'
how about this (generator expression):
>>> f = open("r2h_jvs")
>>> h = (x for x in f)
>>> type(h)
<type 'generator'>`