Iteration Over Open Text File Multiple Times in Python [duplicate] - python

This question already has answers here:
Iterating on a file doesn't work the second time [duplicate]
(4 answers)
Closed 6 years ago.
Surely this has been asked before but I cannot find the question.
As I understand it, in Python (I'm using 3.3 but this is generic to both 2.x and 3.x) you cannot iterate multiple times over an open text file and that this is due to the cursor being moved to the end and does not return to the start on the next iterable loop. Therefore it does not behave like a more typical iterable.
I was wondering how to return the cursor to the start, or at least have two for loops in succession over an open file to be read.
Thanks.

so, you're looking to rewind the file to the start again:
if your file handle is called f do it like this:
f.seek(0)
this won't work on streams, serial ports, pipes, or network sockets: only on regular files.

Related

How can I read a txt file for a specific time limit? [duplicate]

This question already has answers here:
Running a Python script for a user-specified amount of time
(3 answers)
Closed 1 year ago.
I want to read a text file containing many URLs (like around 10k) and I want to read that text file for 30 seconds and only convert those URLs to the list which are being read within that 30 seconds.
Is this possible in python by using any library?
Just give me the direction I will figure out the rest myself.
You can use the time module of python, I suggest you, add a timer in the function if the timer goes to 30sec, then just break it.
you can refer to this.
https://www.geeksforgeeks.org/how-to-create-a-countdown-timer-using-python/
Thanks a lot, guys I solved the problem.
I used start = time.time() for capturing the start time and then I used while(time.time() - start <= 30) for running this loop only for 30 seconds. Inside that I used the .readline() method to read the line one by one and did .append() to append that line into my URLs list.

Python zero as file parameter in open function [duplicate]

This question already has answers here:
Integer File Descriptor "0" in open()
(3 answers)
Closed 1 year ago.
I'm currently puzzling around this piece of code.
What exactly does
open(0)
do?
I already looked up the docs or tried to find something in the internet but no clues.
The codesnippet where this code is used:
map(abs,map(int,open(0).read().split()))
Thanks ^
0 is the file descriptor associated with stdin (1 corresponds to stdout, 2 to stderr). open takes int file descriptors as an argument, not just paths, so passing 0 is legal. This is just a somewhat obscure way to create a file object bound to stdin without needing to import sys.
The flaw with it is that, when it is closed, it will close the file descriptor 0 (since closefd=False was not passed), so sys.stdin will be closed without realizing it (though it'll probably figure it out when if someone tries to use it).

Python print statement dependent on lines following it? [duplicate]

This question already has answers here:
Why doesn't print output show up immediately in the terminal when there is no newline at the end?
(1 answer)
Python print immediately?
(1 answer)
Closed 2 years ago.
I have the following code:
for file_name, content in corpus.items():
print('here')
content = [list(filter(lambda index: index not in remove_indices, content))]
corpus[file_name] = np.array(content).astype(np.uint32)
Where corpus is a 800,000 long dictionary with string keys and array values.
Things were taking forever so I decided to check how fast each iteration was by adding in that print statement.
If I comment the last two lines out it prints lots of heres really fast, so there's no problem with my iterator. What's really weird is that when I uncomment the last two lines, here takes a long time to print, even for the first one! It's like the print statement is somehow aware of the lines that follow it.
I guess my question speaks for itself. I'm in Jupyter notebook, if that helps.

How to read a line in the terminal with python [duplicate]

This question already has answers here:
Capture stdout from a script?
(11 answers)
Closed 3 years ago.
I'm trying to get a already written line in python 3, but I haven't found any function that can read a line from the terminal. It should work something like sys.stdout.read(), or sys.stdout.readline() but this function just throws an error.
If you mean to read from the user/a pipe, then simply use input.
However, from your comments it seems like you want to be able to read from what has already been printed.
To do this, you have a few options. If you don't actually want it to display on the terminal, and you only care about certain part of the output, then you can use contextlib.redirect_stdout and contextlib.redirect_stderr. You can combine this with io.StringIO to capture the output of your application to a string. This has been discussed in the question Capture stdout from a script in Python
However, if you want to have something which provides you both a means of printing to the terminal and giving you the lines, then you will need to implement your own type which inherits from io.TextIOBase or uses io.TextIOWrapper.
Do you mean something like this?
name = input("Enter a name: ")
print(name)

With-As statement versus "=" Assignment? [duplicate]

This question already has answers here:
What is the python "with" statement designed for?
(11 answers)
Closed 7 years ago.
What is the difference of using:
iFile = open("filename.txt",'r')
versus
with open("filename.txt",'r') as iFile:
Is one more efficient or allow more have more methods to access? It appears to me that the with-as statement is temporary and unreferences after the following block ends.
Your first example simply opens the file and assigns the file object to a variable. You will need to manage closing the file yourself (ideally, in a try-finally block so you don't leak the file)
The second snippet uses a context manager to automatically close the file as you exit the with block, including by returning or raising an exception

Categories