I'm writing a program in Python to read a file and turn the file into a list of words. At the moment it gives me four lists (one for each line of the file) The function rstrip() doesn't seem to be working and I'm not sure why.
fname = raw_input("Enter file name: ")
fread = open(fname)
for line in fread:
line = line.rstrip()
lst = line.split()
print lst
I am going to speculate that you want to join the lists from each line. You can do this with list.extend.
lst = []
for line in fread:
line = line.rstrip()
lst.extend(line.split())
print lst
Another way of doing this might be
lst = fread.read().strip().split()
Also, in either case, don't forget to close your file.
fread.close()
Related
if I have a file like:
Flower
Magnet
5001
100
0
and I have a list containing line number, which I have to change.
list =[2,3]
How can I do this using python and the output I expect is:
Flower
Most
Most
100
0
Code that I've tried:
f = open("your_file.txt","r")
line = f.readlines()[2]
print(line)
if line=="5001":
print "yes"
else:
print "no"
but it is not able to match.
i want to overwrite the file which i am reading
You may simply loop through the list of indices that you have to replace in your file (my original answer needlessly looped through all lines in the file):
with open('test.txt') as f:
data = f.read().splitlines()
replace = {1,2}
for i in replace:
data[i] = 'Most'
print('\n'.join(data))
Output:
Flower
Most
Most
100
0
To overwrite the file you have opened with the replacements, you may use the following:
with open('test.txt', 'r+') as f:
data = f.read().splitlines()
replace = {1,2}
for i in replace:
data[i] = 'Most'
f.seek(0)
f.write('\n'.join(data))
f.truncate()
The reason that you're having this problem is that when you take a line from a file opened in python, you also get the newline character (\n) at the end. To solve this, you could use the string.strip() function, which will automatically remove these characters.
Eg.
f = open("your_file.txt","r")
line = f.readlines()
lineToCheck = line[2].strip()
if(lineToCheck == "5001"):
print("yes")
else:
print("no")
Here's the code:
def predator_eat(file):
predator_prey = {}
file.read()
for line in file:
list = file.readline(line)
list = list.split(" ")
predator_prey[list[0]] = list[2]
print(predator_prey)
predator_eat(file)
The text file is three words per line with \n at the end of each line and I previously opened the file and stored the file name as the variable file
using file = open(filename.txt, r)
the print statement ends up being an empty dictionary so it isn't adding keys and values to the dictionary
please help
Your first call to .read() consumes the entire file contents, leaving nothing for the loop to iterate over. Remove it. And that .readline() call does nothing useful. Remove that too.
This should work:
def predator_eat(file):
predator_prey = {}
for line in file:
words = line.split(" ")
predator_prey[words[0]] = words[2]
print(predator_prey)
Cleaning up your code a little:
def predator_eat(f):
predator_prey = {}
for line in f:
rec = line.strip().split(" ")
predator_prey[rec[0]] = rec[2]
return predator_prey
with open(path) as f:
print predator_eat(f)
You basically re declaring python keywords, change file to fileToRead and list something else like totalList or something.
Question:
How can I open a file in python that contains one integer value per line. Make python read the file, store data in a list and then print the list?
I have to ask the user for a file name and then do everything above. The file entered by the user will be used as 'alist' in the function below.
Thanks
def selectionSort(alist):
for index in range(0, len(alist)):
ismall = index
for i in range(index,len(alist)):
if alist[ismall] > alist[i]:
ismall = i
alist[index], alist[ismall] = alist[ismall], alist[index]
return alist
I think this is exactly what you need:
file = open('filename.txt', 'r')
lines = [int(line.strip()) for line in file.readlines()]
print(lines)
I didn't use a with statement here, as I was not sure whether or not you intended to use the file further in your code.
EDIT: You can just assign an input to a variable...
filename = input('Enter file path: ')
And then the above stuff, except open the file using that variable as a parameter...
file = open(filename, 'r')
Finally, submit the list lines to your function, selectionSort.
selectionSort(lines)
Note: This will only work if the file already exists, but I am sure that is what you meant as there would be no point in creating a new one as it would be empty. Also, if the file specified is not in the current working directory you would need to specify the full path- not just the filename.
Easiest way to open a file in Python and store its contents in a string:
with open('file.txt') as f:
contents = f.read()
for your problem:
with open('file.txt') as f:
values = [int(line) for line in f.readlines()]
print values
Edit: As noted in one of the other answers, the variable f only exists within the indented with-block. This construction automatically handles file closing in some error cases, which you would have to do with a finally-construct otherwise.
You can assign the list of integers to a string or a list
file = open('file.txt', mode = 'r')
values = file.read()
values will have a string which can be printed directly
file = open('file.txt', mode = 'r')
values = file.readlines()
values will have a list for each integer but can't be printed directly
f.readlines() read all the lines in your file, but what if your file contains a lot of lines?
You can try this instead:
new_list = [] ## start a list variable
with open('filename.txt', 'r') as f:
for line in f:
## remove '\n' from the end of the line
line = line.strip()
## store each line as an integer in the list variable
new_list.append(int(line))
print new_list
I want my program to read from a .txt file, which has data in its lines arranged like this:
NUM NUM NAME NAME NAME. How could I read its lines into a list so that each line becomes an element of the list, and each element would have its first two values as ints and the other three as strings?
So the first line from the file: 1 23 Joe Main Sto should become lst[0] = [1, 23, "Joe", "Main", "Sto"].
I already have this, but it doesn't work perfectly and I'm sure there must be a better way:
read = open("info.txt", "r")
line = read.readlines()
text = []
for item in line:
fullline = item.split(" ")
text.append(fullline)
Use str.split() without an argument to have whitespace collapsed and removed for you automatically, then apply int() to the first two elements:
with open("info.txt", "r") as read:
lines = []
for item in read:
row = item.split()
row[:2] = map(int, row[:2])
lines.append(row)
Note what here we loop directly over the file object, no need to read all lines into memory first.
with open(file) as f:
text = [map(int, l.split()[:2]) + l.split()[2:] for l in f]
Assuming I have a text file.
My goal is to write a function which receives a number of line to go over in the text file and returns a list, each cell in the list containing one word exactly from that line.
Any idea of how doing this ?
thanks
If you are working with small files:
def get_words(mifile, my_line_number):
with open(mifile) as f:
lines = f.readlines()
myline = lines[my_line_number] #first line is 0
return myline.split()
you get all the file lines in the list lines. This is not very efficient for VERY big files. In that case probably it would be better to iterate line by line until you arrive to the chosen line.
Given the filename and the line number (lineno), you could extract the words on that line this way:
Assuming the lineno is not too large:
import linecache
line = linecache.getline(filename, lineno)
words = line.split()
Or, if the lineno is large:
import itertools
with open(filename,'r') as f:
line = next(itertools.islice(f,lineno-1,None))
words = line.split()
This,of course,assumes that words are separated by spaces--which may not be the case in hard-to-parse text.