I have a file called data.txt with a student numbers and names:
123, Bobbie Smith
456, Suzie Lan
789, Alex Palmer
What i'm trying to achieve is printing these information in sentences like this:
Bobbbie Smith has student number: 123
Suzie lan has student number: 456
Alex Palmer has student number: 789
So what I tried to do is putting every line on data.txt in a seperate list inside a list using:
file = open("data.txt", "r")
studentInfo = file.readlines()
file.close()
lines = [[line] for line in studentInfo]
>>> print(lines)
[['123, Bobbie Smith\n'], ['456, Suzie Lan\n'], ['789, Alex Palmer']]
Is this to good direction or should I do this using a completely different way?
use csv to avoid strip lines.
import csv
with open('data.txt', 'r', encoding='utf-8') as csv_f:
reader = csv.reader(csv_f)
for line in reader:
print('{x[1]} has student number: {x[0]}'.format(x=line))
You don't want to use file as a variable name, as it is a function. So you basically override it (thanks #Mark Tolonen).
You can slightly modify it and use context manager to read the file, and using string.format print the data in a readable fashion
with open("data.txt", "r") as f:
lines = [line.split(',') for line in f.readlines()]
for s in lines:
print '{} has student number: {}'.format(s[1].strip(), s[0].strip())
Output:
Bobbie Smith has student number: 123
Suzie Lan has student number: 456
Alex Palmer has student number: 789
I'm striping new lines from line because print statement prints a new line by default for every iteration
one way is using the numpy library
import numpy as np
x, y = np.loadtxt("data.txt", dtype = str, delimiter = ',', unpack = True)
for (i,j) in zip(x,y):
print(j+" has student number: "+i)
Here's a couple of ways to achieve what you want using re:
If you don't need to store the processed lines and just wanna print the output directly:
with open("data.txt", "r") as f:
for l in f.readlines():
try:
age, name = re.findall(r'\s*(\d+),\s*(.*)', l)[0]
print('{} has student number: {}'.format(name, age))
except:
pass
If you want to store the processed lines as a list of tuples, maybe something like this would do it:
with open("data.txt", "r") as f:
lines = [v[0]
for v in [re.findall(r'\s*(\d+),\s*(.*)', l) for l in f.readlines()] if v]
for age, name in lines:
print('{} has student number: {}'.format(name, age))
Related
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.
Firstly I use this:
with open(filename) as fp:
for i, line in enumerate(fp):
print(i)
print(line)
if i == index:
break
else:
continue
This makes me able to output each line until ( i ) reaches the amount of the index variable, but this is not all I want, I want to read a file which looks a bit like this :
John|Graham|JOB|AGE
Philip|Jefferson|JOB|AGE
I want to be able to parse this data into corresponding variables, but! I want to be able to specify which line to read from, so that I can read line 1, parse the data from there, and then line 2, but not as in a loop!, which is the important part.
I want to be able to set the variable ( index ) to let's say 2
then line 2 will parse the first segment "Philip" into the variable NAME.
and so on.
I hope you understand!, I have been so frustrated that I have not been able to come up with a solution.
Here's something that should work:
first we need to get all the lines read into a list.
>>> with open('in.txt', 'r') as f:
>>> lines = f.read().splitlines()
now we can index nicely in:
>>> print(lines[0])
John|Graham|JOB|AGE
Okay, now we want to split each line into the data we need.
>>> first = lines[0]
>>> info = first.split('|')
['John', 'Graham', 'JOB', 'AGE']
And then to put everything into a variable:
>>> NAME, LASTNAME, JOB, AGE = info
>>> print(NAME)
John
>>> print(LASTNAME)
Graham
Putting it all together:
with open('in.txt', 'r') as f:
lines = f.read().splitlines()
def get_info(lines, line_num):
line = lines[line_num]
return line.split('|')
NAME, LASTNAME, JOB, AGE = get_info(lines, 0)
print(NAME) # Prints "John"
If you don't want to read in the whole file at once, you can use the same techniques in your script:
with open(filename) as fp:
for i, line in enumerate(fp):
print(i)
print(line)
if i == index:
NAME, LASTNAME, JOB, AGE = line.split('|')
break
You can use a dictionary to allow you to access each line by index:
the_dict = {i:a.strip('\n') for i, a in enumerate(open('filename.txt'))}
Output:
{0: 'John|Graham|JOB|AGE', 1: 'Philip|Jefferson|JOB|AGE'}
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]
I want to have a list of names such as "john, jack, daniels, whisky, susan, alex" in a .txt file called 'names'.
Now, I want to import that file into my 'script' and use the import random module.
This is what I have:
import random
name = ( "jay" , "luis" , "bob" , "sofi", "susan" )
x = random.sample(name,input( "please enter the number of volunteers needed" ))
print x
instead of having name = ( xxxxxxxxxxxxx ), I want to have name = .txt file.
Everytime i want to change the names I can just change it in the .txt file.
I'm trying to make a program for my schools volunteer club, so the number of volunteers chosen is at random and not biased. That way everyone has a somewhat fair chance. :]
file = open('myFile.txt', 'r')
names = file.read().split(',')
file.close()
Use that in place of your name = ... line and you should be good to go.
You can read more about reading and writing files in Python here.
Note that I assumed you'll have a comma-delimited list in the file. You can also put each name on a separate line and do names = file.readlines() instead.
welcome to python :-]
how about something like this?
import random
fid = open('names.txt', 'r')
names = fid.readlines()
number_needed = raw_input('please enter the number of volunteers needed: ')
print random.sample(names, int(number_needed))
You could simply fill a text file with names delimited by line:
with open('names.txt') as f:
names = f.read().splitlines()
Assuming a list of names in names.txt, one per line (and that you don't have a hundred million names in there):
import random
number_of_volunteers = 4
print random.sample([n[:-1] for n in open("./names.txt").readlines()], number_of_volunteers)
Where:
$ cat rand_nms.txt
jay
luis
bob
sofi
Then:
import random
contents=[]
with open("rand_nms.txt") as rnd:
for line in rnd:
line=line.strip()
contents.append(line)
print contents
print "random name:", contents[random.randint(0,len(contents)-1)]
Result:
['jay', 'luis', 'bob', 'sofi', 'susan']
random name: luis
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()