First off I am aware this kind of question has already been posted but none of those things seemed to be working for me.
I have a text file that looks like this:
"foo","bar","green","white"
and so on.
I want to import the entire content to a list like this:
txtfile = open("H:/Python/colors.txt", "r")
list1 = [txtfile.read()]
print (list1[0])
but python does not recognize the words as seperate list items, so that list1[0] gives me the entire content and list1[1] does not exist.
Why does python do that and how do I avoid it?
You no need to specify separately list and can write as:
with open("stopwords.txt", "r") as fd:
var = fd.readline()
list1 = list()
temp = eval(var)
list1 = [ele for ele in temp]
print(list1)
Explanation:
Read the line using readline and get that into var and that is a string datatype. Now using eval evaluate it. Now using list comprehension you can get required output
You can use:
list1 = txtfile.read().split(',')
Try this.
txtfile = open("H:/Python/colors.txt", "r")
list1 = txtfile.read().split(",")
print(list1[0])
Try using the mentioned below code:
file=open("H:/Python/colors.txt","r")
for line in file:
fields=line.split(",")
print(fields[0],fields[1],fields[2],fields[3])
Related
[2, 'hello', 3, 'good'] - is stored in myfile.txt on one line
with open(myfile,'r') as f:
myList = f.readlines()
but when I try to retrieve the first index, so "2' by using myList[0], the first square brackets is retrieved.
How can I set the imported line into a list?
use the ast module to convert the string to a list object
Ex:
import ast
with open(myfile,'r') as f:
data= f.read()
myList = ast.literal_eval(data)
.readlines() method reads lines of text from file, separated with the new line character and returns a list, containing those lines, so that's not the case.
You could have read the contents of the file and eval it like this:
with open(myfile,'r') as f:
my_list = eval(f.read())
Note, that the usage of eval is considered to be a really bad practice, as it allows to execute any python code written in the file.
You can use the json module for this (since a list is a valid json object):
import json
with open(myfile) as f:
myList = json.load(f)
You could do:
mylist = mylist[1:-1].split(",")
[1:-1] gets rid of brackets
I am just learning to code and am trying to take an input txt file and break into a list (by row) where each row's characters are elements of that list. For example if the file is:
abcde
fghij
klmno
I would like to create
[['a','b','c','d','e'], ['f','g','h','i','j'],['k','l','m','n','o']]
I have tried this, but the results aren't what I am looking for.
file = open('alpha.txt', 'r')
lst = []
for line in file:
lst.append(line.rstrip().split(','))
print(lst)
[['abcde', 'fghij', 'klmno']]
I also tried this, which is closer, but I don't know how to combine the two codes:
file = open('alpha.txt', 'r')
lst = []
for line in file:
for c in line:
lst.append(c)
print(lst)
['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o']
I tried to add the rstrip into the lst.append but it didn't work (or I didn't do it properly). Sorry - complete newbie here!
I should mention that I don't want newline characters included. Any help is much appreciated!
This is very simple. You have to use the list() constructor to make a string into its respective characters.
with open('alpha.txt', 'r') as file:
print([list(line)[:-1] for line in file.readlines()])
(The with open construct is just an idiom, so you don't have to do all the handling with the file like closing it, which you forgot to do)
If you want to split a string to it's charts you can just use list(s) (where s = 'asdf'):
file = open('alpha.txt', 'r')
lst = []
for line in file:
lst.append(list(line.strip()))
print(lst)
You are appending each entry to your original list. You want to create a new list for each line in your input, append to that list, and then append that list to your master list. For example,
file = open('alpha.txt', 'r')
lst = []
for line in file:
newLst = []
for c in line:
newLst.append(c)
lst.append(newLst)
print(lst)
use a nested list comprehension. The outer loop iterates over the lines in the file and the inner loop over the characters in the strings of each line.
with open('alpha.txt') as f:
out = [[char for char in line.strip()] for line in f]
req = [['a','b','c','d','e'], ['f','g','h','i','j'],['k','l','m','n','o']]
print(out == req)
prints
True
I have a text file called "test", and I would like to create a list in Python and print it. I have the following code, but it does not print a list of words; it prints the whole document in one line.
file = open("test", 'r')
lines = file.readlines()
my_list = [line.split(' , ')for line in open ("test")]
print (my_list)
You could do
my_list = open("filename.txt").readlines()
When you do this:
file = open("test", 'r')
lines = file.readlines()
Lines is a list of lines. If you want to get a list of words for each line you can do:
list_word = []
for l in lines:
list_word.append(l.split(" "))
I believe you are trying to achieve something like this:
data = [word.split(',') for word in open("test", 'r').readlines()]
It would also help if you were to specify what type of text file you are trying to read as there are several modules(i.e. csv) that would produce the result in a much simpler way.
As pointed out, you may also strip a new line(depends on what line ending you are using) and you'll get something like this:
data = [word.strip('\n').split(',') for word in open("test", 'r').readlines()]
This produces a list of lines with a list of words.
I'm trying to create a list of text files from a directory so I can extract key data from them, however, the list my function returns also contains a list of the file pathways as the first item of the list. I've tried del full_text[0] which didn't work, as well as any other value, and also the remove function. Any ideas as to why this might be happening?
Thanks
import glob
file_paths = []
file_paths.extend(glob.glob("C:\Users\12342255\PycharmProjects\Sequence diagrams\*"))
matching_txt = [s for s in file_paths if ".txt" in s]
print matching_txt
full_text = []
def fulltext():
for file in matching_txt:
f = open(file, "r")
ftext = f.read()
all_seqs = ftext.split("title ")
print all_seqs
full_text.append(fulltext())
print full_text
You can use slicing to get rid of the first element - full_text[1:]. This creates a copy of the list. Otherwise, you can full_text.pop(0) and resume using full_text
I see at least two ways to do so:
1) you can create a new list from first position e.g. newList = oldList[1:]
2) use remove method - full_text.remove(full_text[0])
So I am getting a list of items from a MySQL database, working with Python, Flask, Flask-SQLAlchemy. I am already incrementing rows of this list like this:
for file in files:
file.last_viewed_time = datetime.utcnow()
db.session.commit()
But I want to extract one more thing from this list (files), a list of another attribute.
How can I add these to a new list, something like:
mylist = []
for file in files:
new = file.attribute
add new to mylist
Or is this a convoluted way of doing it, can I copy these values in a better way?
Use list.append:
mylist = []
for f in files:
new = f.attribute
mylist.append(new)
Or using list comprehension:
mylist = [f.attribute for f in files]
mylist = [f.attribute for f in files] # don't use file, it's the name of a builtin-function
try this
mylist = []
for file in files:
new = file.attribute
mylist.append(new)