So, i have a nested list written into a file.txt
students = []
info = []
name = input("Name: ")
age = input("Age: ")
info.append(name)
info.append(age)
students.append(info)
my_file = open("file.txt", "a")
for data in students:
my_file.write("%s\n" % data)
my_file.close()
The contents in the file are in this format:
['john', '19']
['nick', '20']
Afterwards, i'm using nested loop to access the content of file.txt
my_file = open("file.txt", "r")
search_keyword = input("Please Enter Student Name: ")
for students in my_file:
for info in students:
print(info)
Expected output:
john
19
nick
20
Actual output:
j
o
h
n
1
9
n
i
c
k
2
0
Can someone explain why the inner list is missing after extracting from a file, as the loop treats each individual alphabet as an element.
Uh, I'm not 100% sure but maybe try: my_file.writelines("")
This seems a good candidate for pickle since you have a Python data structure you want to preserve.
import pickle
lol = [['john', '19'],['nick', '20']]
with open('lol.pickle','wb') as f:
pickle.dump(lol,f)
del lol
print(lol)
# NameError: name 'lol' is not defined
with open('lol.pickle','rb') as f:
lol = pickle.load(f)
print(lol)
# [['john', '19'], ['nick', '20']]
You have read the data as a string, so when you iterate you are iterating through elements of a string, not elements of a list.
I am assuming that you are learning python. The current program works, but is not the best way to do it. You should try using csv or pickle. However, it is always good to start from basic! :D
students = []
info = []
name = input("Name: ")
age = input("Age: ")
info.append(name)
info.append(age)
students.append(info)
with open("file.txt", "a") as my_file:
for data in students:
my_file.write("%s,%s\n" % (data[0], data[1])) # this will write in file like name,age
After that you can retrieve like
search_keyword = input("Please Enter Student Name: ")
with open("file.txt", "r") as my_file:
for students in my_file:
for info in students.split(','): # We split it based on commas to get the desired output
print(info)
The mistake you were making is that when you tried for info in students you were iterating over characters in the string rather than the actual information.
Notice how we have used with open this will do all the file handling automatically.
Iterating over file-like objects produces lines
for students in my_file:
On each iteration students will be a line of text.
Iterating over text produces individual characters.
for info in students:
On each iteration info will be a character.
If your text files have string representations of python objects you can use ast.literal_eval to evaluate the objects.
import ast
with open('file.txt') as f:
for line in f:
thing = ast.literal_eval(line)
print(thing)
for item in thing:
print(item)
As mentioned in the docs, ast.literal_eval Safely evaluate an expression node or a string with emphasis on safe - it shouldn't evaluate destructive or unwanted Python statements.
You would be better off using one of the built-in data persistence modules or perhaps json or even xml to save your data.
Related
I am trying to count up unique names that start with "From:" from a file name. However, I keep getting a long list of numbers. What is my code actually reading and how do I fix this?
count = 0
name = []
fname = input("What is your file name? Enter it here: ")
try:
fname = open(fname)
name = set(f.readlines())
except:
print ("That file does not exist.")
for name in fname:
if name.startswith("From:"):
count = len(name)
print (count)
We can make use of set to hold all required names and find its length to get the count:
file_name = input("What is your file name? Enter it here: ")
s = set()
with open(file_name) as f:
for name in f:
if name.startswith('From:'):
s.add(name)
print(len(s))
Try this:
words = []
count = 0
with open ("unique.txt","r") as f:
# Get a list of lines in the file and covert it into a set
words = set(f.readlines())
FromWords=[]
for word in words:
if word.startswith("From:"):
FromWords.append(word)
print(len(FromWords))
First, we filter out all duplicate words and then look for the words which start with From: and this may aid in faster processing if you're dealing with the big amount of data.
let me know if you need any help in this regard.
My file reads the teamNames.txt file which is:
Collingwood
Essendon
Hawthorn
Richmond
Code:
file2 = input("Enter the team-names file: ") ## E.g. teamNames.txt
bob = open(file2)
teamname = []
for line1 in bob: ##loop statement until no more line in file
teamname.append(line1)
print(teamname)
The output is:
['Collingwood\n', 'Essendon\n', 'Hawthorn\n', 'Richmond\n']
I want to make it so the output will be:
Collingwood, Essendon, Hawthorn, Richmond
One option is to use the replace() function. I've modified your code to include this function.
file2= input("Enter the team-names file: ") ## E.g. teamNames.txt
bob =open(file2)
teamname = []
for line1 in bob: ##loop statement until no more line in file
teamname.append(line1.replace("\n",""))
print(teamname)
Would give you the output:
['Collingwood', 'Essendon', 'Hawthorn', 'Richmond']
You could then modify teamname to get your requested output:
print(", ".join(teamname))
What about
for line1 in bob:
teamname.append(line1.strip()) # .strip() removes the \n
print (', '.join(teamname))
The .join() does the final formatting.
Update. I now think a more pythonistic (and elegant) answer would be:
file2 = input("Enter the team-names file: ") ## E.g. teamNames.txt
with open(file2) as f:
teamname = [line.strip() for line in f]
print (', '.join(teamname))
The with statement ensures the file is closed when the block finishes. Instead of doing the for loop, it now uses a list comprehension, a cool way to create a list by transforming the elements from another list (or from an iterable object, like file).
The join method works well but you can also try using a for loop.
for name in teamname: # takes each entry separately
print name
I am in need of some help, I'm currently doing an online python course and i can seem to get the desire result to complete the assignment.
basically, there is a text document which i need to call by using "raw_input" i then use"open()" function and then i have an empty "list()"
Now i run a "for" loop for each line in my .txt doc, i need to "r.strip()" all the white space, which leaves me with a 4 live .txt document ( .txt file will be at the bottom of the ask ) now i have to ".split()" those lines into words. now from the i need to loops through those words and ".append()" each word that isnt already in the list, then ".sort()" then print ... hopefully by that stage it looks as the desired output.
Just to make me feel a little better this is the first time im doing any sort of coding. so if you could explain where and why im going wrong that would be great.
CODE SO FAR - currently produces an error
fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
a = line.rstrip()
b = a.split()
for words in b:
if words not in lst:
print lst
.TXT DOCUMENT
But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
p.s - Theres no point in changing the .txt to one line because the code it wont work in the grader. Ive tried (got the desired output, wrong code)
Please, you help would be greatly appreciated.
if there is anymore info you need, ill try provide it.
This will read the file, add words to list, sort the list, and then print it.
fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
a = line.rstrip()
b = a.split()
for words in b:
if words not in lst:
lst.append(words)
lst.sort()
print lst
fh.close()
lst.append(element) will add the element into the list lst.
lst.sort() will sort the list lst alphabetically.
Check out the document => Lists
l = list()
with open('inp.txt') as inp:
for each_line in inp:
a = each_line.strip()
l += a.split()
print set(l)
use with keyword as it's a better practice as it would close your file after operation.and for the unique portion use set() which only accepts unique elements
You could also make use of set which is like a list but without duplicates. This means you don't have to check for duplicates yourself, since set will do it for you auto-magically.
eg:
fname = raw_input("Enter file name: ")
fh = open(fname)
lst = set()
for line in fh:
a = line.rstrip()
b = a.split()
for words in b:
lst.add(words)
lst = list(lst)
lst.sort()
print lst
Try list comprehension to generate list, use set to remove duplicate entry
lst = [words for line in open(fname) for words in line.rstrip().split()]
lst = list(set(lst))
lst.sort()
print lst
First of all my program must work with several files and 10 inputs in every file, this is just little piece, to be clear.
My code right now:
code = input(">> ")
print("\nPress <Enter> and parameter will be same!")
f = open("komad_namestaja.txt", "r")
allDATA = f.readlines()
f.close()
for line in allDATA:
lst = line.split("|")
if code == lst[0]:
print("\nName :", lst[1])
name = input("New Name >> ")
if name == "":
name = lst[1]
f = open("komad_namestaja.txt", "r")
allDATA = f.read()
f.close()
newdata = allDATA.replace(lst[1], name)
f = open("komad_namestaja.txt", "w")
f.write(newdata)
f.close()
print("\ndestination :", lst[2])
destination = input("New destination >> ")
if destination == "":
destination = lst[2]
#Writting function here
File before:
312|chessburger|Denmark
621|chesscake|USA
code input: 312
name input: Gyros
destination input: Poland
file after inputs:
312|Gyros|Poland
621|chesscake|USA
Problem is this replacing in file I cant write 7 lines code every time, because I have 10 x 5 inputs, and also I tried everything and cant make function of this.
I must write some function for reading/writing/replacing or replacing all inputs after last one.
You don't have to read the file in every time to modify one field, write it out, reopen it to change another field, and so on. That's inefficient, and in your case, causes code explosion.
Since your files are small, you could just read everything into memory at once and work on it in memory. Your code is easy to map via a dict.
Here's a function that takes a filename and converts your file into a dictionary.
def create_mapping(filename):
with open(filename, 'r') as infile:
data = infile.readlines()
mapping = {int(k): (i,d) for k,i,d in
(x.strip().split('|') for x in data)}
# Your mapping now looks like
# { 312: ('cheeseburger', 'Denmark'),
# 621: ('chesscake', 'USA') }
return mapping
Then you can update the mapping from user input since it's just a dictionary.
Once you want to write the file out, you can just serialize out your dictionary by iterating over the keys and rejoining all the elements using |.
If you want to use lists
If you want to stick with just using lists for everything, that is possible.
I would still recommend reading your file into a list, like so:
def load_file(filename):
with open(filename, 'r') as infile:
data = infile.readlines()
items = [(int(k), i, d) for k,i,d in
(x.strip().split('|') for x in data]
# Your list now looks like
# [(312, 'cheeseburger', 'Denmark'), (621, 'chesscake', 'USA')]
return items
Then when you get some user input, you have to traverse the list and find the tuple with what you want inside.
For example, say the user entered code 312, you could find the tuple that contained the 312 value from the list of tuples with this:
items = load_file(filename)
# Get input for 'code' from user
code = int(input(">> "))
# Get the position in the list where the item with this code is
try:
list_position = [item[0] for item in items].index(code)
# Do whatever you need to (ask for more input?)
# If you have to overwrite the element, just reassign its
# position in the list with
# items[list_position] = (code, blah, blah)
except IndexError:
# This means that the user's entered code wasn't entered
# Here you do what you need to (maybe add a new item to the list),
# but I'm just going to pass
pass
I have a .txt file like this:
John 26
Mary 48
Nick 34
I want import them and put them in a list so that I can find specific elements. For example age[1] would have the value 48, name[1] the value Mary etc.
I tried doing
import sys,random
f = open('example.txt', 'r')
for line in f:
tokens=line.split()
a=tokens[0]
print a[1]
but the result of print a[1] is the second letter of each string.
Instead of a[1], you want tokens[1].
This is the value of a, which is the first element of tokens:
Nick
But the second element of tokens is the age:
"34"
As #user mentioned, you probably wanted to have it as integer, not a string. You can convert it to integer:
a = int(tokens[1])
#thefourtheye proposed a nice solution. I think i'll propose to store it in a dictionary:
with open('example.txt') as f:
ages = {}
for line in f:
d = line.split()
ages[d[0]] = int(d[1])
And here is ages:
{'John':26, 'Mary':48, 'Nick':34}
To retrieve the age of John:
print(ages['John'])
Hope this helps!
While reading from a file, always use with, so that you dont have to worry about closing the file.
Then, you can read lines and split them and finally unzip them like this
with open('Input.txt', 'r') as inFile:
names, ages = zip(*(line.rstrip().split() for line in inFile))
print names, ages
Output
('John', 'Mary', 'Nick') ('26', '48', '34')
You can access the individual names and ages like this
names[0], ages[0]