I have this code:
file_open=open("/python32/doc1.txt","r")
file=a1.read().lower()
for line in file:
line_word=line.split()
This works fine. But if I print line_word it would be printed continuously.
I like to store in some variable, so that I may print a line of my choice and manipulate them at my choice.
Is there any way to solve this problem?
Generally I append to a list and do the necessary stuff, but for bigger files it is really problematic.
If anyone can kindly suggest a solution.
You don't need to call .read() to iterate over the lines of a file.
with open("/python32/doc1.txt", "r") as f:
for line in f:
line_word = line.lower().split()
Does this help?
file_open=open("/python32/doc1.txt","r")
file=a1.read().lower()
line_word = []
for line in file.splitlines():
line_word.append(line.split())
Related
What I have attempted to do is read the file and store the information in separate lists. For this program a small example file is used to first ensure the code works but this program will deal with photos in the 100,000's and this doesn't seem like the best way to index the file for optimal efficiency. This is what I have so far:
with open('a_example.txt') as example_file:
content = [i.strip() for i in example_file.readlines()]
number_of_photos = content[0]
del content[0] #remove the numphoto info
for j in content:
orientation_of_photo.append(j[0])
number_of_tags.append(j[2])
The only reason I can tell you are indexing the file is to get the first line.
You can use next() to get this, then continue on with the loop
with open('a_example.txt') as example_file:
number_of_photos = next(example_file).strip()
for line in example_file:
j = line.strip()
orientation_of_photo.append(j[0])
number_of_tags.append(j[2])
I'm trying to write a simple Phyton script that alway delete the line number 5 in a tex file, and replace with another string always at line 5. I look around but I could't fine a solution, can anyone tell me the correct way to do that? Here what I have so far:
#!/usr/bin/env python3
import od
import sys
import fileimput
f= open('prova.js', 'r')
filedata = f,read()
f.close ()
newdata = "mynewstring"
f = open('prova.js', 'w')
f.write(newdata, 5)
f.close
basically I need to add newdata at line 5.
One possible simple solution to remove/replace 5th line of file. This solution should be fine as long as the file is not too large:
fn = 'prova.js'
newdata = "mynewstring"
with open(fn, 'r') as f:
lines = f.read().split('\n')
#to delete line use "del lines[4]"
#to replace line:
lines[4] = newdata
with open(fn,'w') as f:
f.write('\n'.join(lines))
I will try to point you in the right direction without giving you the answer directly. As you said in your comment you know how to open a file. So after you open a file you might want to split the data by the newlines (hint: .split("\n")). Now you have a list of each line from the file. Now you can use list methods to change the 5th item in the list (hint: change the item at list[4]). Then you can convert the list into a string and put the newlines back (hint: "\n".join(list)). Then write that string to the file which you know how to do. Now, see if you can write the code yourself. Have fun!
print("writing text to file")
prompt = '>'
data = [input(prompt) for i in range(3)]
with open('textfile.txt', 'w') as testfile:
testfile.write("\n".join(data))
with open('textfile.txt', 'r') as testfile:
print (testfile.read())
data = [line.strip('\n') for line in testfile]
data2 = testfile.readlines()
print(data)
print(data2)
After learning how to read and write from text files I have been trying to use
for line in textfile
But to no avail. In my above code both data and data2 print as empty arrays which makes me think I am doing something really wrong. Before I could get testfile.readlines() to work but I was never able to use a for loop. For some reason it wouldn't even enter the loop (even if I do a standard for loop outside of list comprehension).
Does anyone have any ideas what I am doing incorrectly? I could not find anyone else who has this problem.
When you called
print (testfile.read())
That put the file pointer to the end of the file. You need to bring it back to the beginning again by calling
testfile.seek(0)
After that, so that when the next file reading method is called it will be able to read the file from the beginning again. Likewise, after that list comprehension assignment to data you will need to do the same so that data2 can be populated.
The first thing you do is print(testfile.read()) which reads the entire contents of the file. After that any read is going to fail. You need to seek back to the beginning of the file:
testfile.seek(0)
The code i have right now is this
f = open(SINGLE_FILENAME)
lines = [i for i in f.readlines()]
but my proffessor demands that
You may use readline(). You may not use read(), readlines() or iterate over the open file using for.
any suggestions?
thanks
You could use a two-argument iter() version:
lines = iter(f.readline, "")
If you need a list of lines:
lines = list(lines)
First draft:
lines = []
with open(SINGLE_FILENAME) as f:
while True:
line = f.readline()
if line:
lines.append(line)
else:
break
I feel fairly certain there is a better way to do it, but that does avoid iterating with for, using read, or using readlines.
You could write a generator function to keep calling readline() until the file was empty, but that doesn't really seem like a large improvement here.
How would I pull text from a specific text line, inside a text file using Python?
If you want to read the 10th line:
with open("file.txt") as f:
for i in range(9):
f.next()
print f.readline()
This doesn't read the whole file in memory.
The simplest method:
print list( open('filename') )[line_number]
That's gonna read in the whole file which may not be a good idea. A more efficient technique would depend on how you are using it.
The following Python example should extract the correct line number, but it is horribly inefficient:
f = open('file.txt')
print f.readlines()[line_number]