How to output only the string in list data? - python

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

Related

How to read IDs from a .txt file?

I'm doing a database using txt files in which the data is stores like this: idTheme|Name|Hours.
For example: 45|Object Oriented Programming|12
I need to print the line of text with the idTheme I'm given, so I did this:
print("Give me the ID")
id_search = input("> ")
for line in file:
for x in line:
if id_search != x:
break
else:
print(line)
break
Since the ID is always the first character in each line I thought thst would work.
Problem is, this only works when the ID is 1 character long.
I was thinking on putting the info on a list and using a split("|") to divide it but that would put all the info in the list, not only the IDs.
Any suggestions are apreciated.
You could use split as you said and just use index 0 to get the ID.
for line in file:
id = line.split("|")[0]
if id_search == id:
print(line)
You can invert your if statement so if the id is equal to the search term it prints the line, otherwise nothing happens. You also avoid looping through the entire line.
You can use somethign like:
with open("text.txt") as f:
lines = [x.strip() for x in list(f) if x]
print("Give me the ID")
id_search = input("> ").strip()
if id_search:
for line in lines:
id, name, otherid = line.split("|")
if id_search == id:
print(line)
break
Demo

Nested list missing after read from file

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.

Python search for input in txt file

When my script is run, it asks for an input. That input is then checked to see if it's in a text file. If it is, text is printed. The code I have below is what I have but it doesn't seem to be working, any help would be greatly appreciated!
discordname = input("What's your discord name?: ")
file = open('rtf.txt')
for line in file:
line.strip().split('/n')
if line.startswith(discordname):
file.close()
print("works")
The expression
line.strip().split('\n')
is not mutating the information bound to the name line, which remains unchanged. Instead it returns a new value. You need to bind that new value to a name in order to use use it. This example might help:
In [1]: a = " v "
In [2]: a.strip()
Out[2]: 'v'
In [3]: a
Out[3]: ' v '
In [4]: b = a.strip()
In [5]: a
Out[5]: ' v '
In [6]: b
Out[6]: 'v'
Then split('\n') (note that you probably want \ instead of /) further returns a list of substrings split by newlines. Note that this is not very useful because for line in file: already splits over lines so the list would have one element at most, and so you should omit it.
Here is the Solution:
discordname = input("What's your discord name?: ")
with open('rtf.txt', 'r') as f:
for line in f.readlines():
if line.startswith(discordname):
print ("it works")
I hope it resolve you're problem.thanks
You are probably trying to get strings as input as well. I suggest this:
discordname = raw_input("What's your discord name? ")
with open('rtf.txt') as f:
for line in f:
if discordname in line:
print "works"
You are trying to make the code more complex. Firstly to open a text file use 'with', because it is more flexible and doesn't need closing. Then, instead of using strip, you can use readlines(). This function converts each line into a list or you can also use method read(), which displays all results as it is.
So,
By using readlines, you can look through the user input in a line as a list, and by using read, you can look through each words. Here is the Solution:
discordname = input("What's your discord name? ")
with open('rtf.txt') as file:
contents = file.readlines()
if discordname in contents:
print("It exits")
Works for me, Optimized code is:
result = any(line.startswith(discordname) for line in file.splitlines())
if(result):
file.close()
print "works"

Deleting a line in file containing exact string (Python)

import re
print "List of names:"
f=open('names.txt','r') #look below
lines = f.readlines()
for line in lines:
info = line.split('|')
names = info[0]
print names
name = raw_input("Enter the name of the person you want to delete: ")
f.close()
f = open('names.txt','w')
for line in lines:
if not re.match(name,line):
f.write(line)
break
print "That person doesn't exist!"
names.txt :
John|22|Nice
Johnny|55|Better than John
Peter|25|The worst
So, when you run the program, list of names is printed and then you have to enter the name of the person whose line you want to delete.
The problem is, if I enter John, it deletes the first and the second line, but I want only the first line to be deleted. My guess is that I'm not doing re.match() right. I tried re.match(name,names) but that doesn't work either.
So, the string you enter into name should be compared to the strings in names , and if there's an exact match, it should delete the line that has name as the first element.
I found a lot of similar problems but my function contains everything combined and I can't figure it out.
re.match matches the string at the beginning of the string. You may add word delimeter to your expression
name + r'\b'
but in your case, re is an overkill, simple comparison will do
name == line.partition('|')[0]
BTW, if you need to split only once at the beginning - or end - partition and rpartition functions are better options
EDIT
Timing:
>>> timeit('line.startswith(name+"|")', 'line="John|22|Nice";name="John"')
0.33100164101452345
>>> timeit('line.partition("|")[0] == name', 'line="John|22|Nice";name="John"')
0.2520693876228961
>>> timeit('re.match(name+r"\b", line)', 'import re; line="John|22|Nice";name="John"')
1.8754496594662555
>>> timeit('line.split("|")[0] == name', 'line="John|22|Nice";name="Jonny"')
0.511219799415926
Especially for Padraick
>>> timeit('line.partition("|")[0] == name', 'line="John|22|Nice";name="John"')
0.27333073995099083
>>> timeit('line.split("|", 1)[0] == name', 'line="John|22|Nice";name="John"')
0.5120651608158937
Frankly - I am surprised myself
with open("in.txt") as f:
lines = f.readlines()
name = raw_input("Enter the name of the person you want to delete: ").lower() + "|"
ln = len(name)
for ind, line in enumerate(lines):
if name == line[:ln].lower():
lines[ind:ind+1] = []
break
with open("in.txt","w") as out:
out.writelines(lines)
If you want to remove all John's etc.. don't break just keep looping and writing, as it stands we erase the first "John" we find. The fastest way is to just index.

I am having a problem with my python program that im running

From an input file I'm suppose to extract only first name of the student and then save the result in a new file called "student-­‐firstname.txt" The output file should contain a list of
first names (not include middle name). I was able to get delete of the last name but I'm having problem deleting the middle name any help or suggestion?
the student name in the file look something like this (last name, first name, and middle initial)
Martin, John
Smith, James W.
Brown, Ashley S.
my python code is:
f=open("studentname.txt", 'r')
f2=open ("student-firstname.txt",'w')
str = ''
for line in f.readlines():
str = str + line
line=line.strip()
token=line.split(",")
f2.write(token[1]+"\n")
f.close()
f2.close()
f=open("studentname.txt", 'r')
f2=open ("student-firstname.txt",'w')
for line in f.readlines():
token=line.split()
f2.write(token[1]+"\n")
f.close()
f2.close()
Split token[1] with space.
fname = token[1].split(' ')[0]
with open("studentname.txt") as f, open("student-firstname.txt", 'w') as fout:
for line in f:
firstname = line.split()[1]
print >> fout, firstname
Note:
you could use a with statement to make sure that the files are always closed even in case of an exception. You might need contextlib.nested() on old Python versions
'r' is a default mode for files. You don't need to specify it explicitly
.readlines() reads all lines at once. You could iterate over the file line by line directly
To avoid hardcoding the filenames you could use fileinput. Save it to firstname.py:
#!/usr/bin/env python
import fileinput
for line in fileinput.input():
firstname = line.split()[1]
print firstname
Example: $ python firstname.py studentname.txt >student-firstname.txt
Check out regular expressions. Something like this will probably work:
>>> import re
>>> nameline = "Smith, James W."
>>> names = re.match("(\w+),\s+(\w+).*", nameline)
>>> if names:
... print names.groups()
('Smith', 'James')
Line 3 basically says find a sequence of word characters as group 0, followed by a comma, some space characters and another sequence of word characters as group 1, followed by anything in nameline.
f = open("file")
o = open("out","w")
for line in f:
o.write(line.rstrip().split(",")[1].strip().split()+"\n")
f.close()
o.close()

Categories

Resources