I am having trouble converting this code snippet into reading only the first line of the file, rather than opening it random.
Can somebody help?
lines = open('myfile.txt').read().splitlines()
account =random.choice(lines)
If you only want the first line, then only read the first line.
with open('myfile.txt') as f:
line = f.readline()
Above, f.readline() reads until a newline or EOF.
You could take advantage of the fact that the file object itself is iterable:
>>> with open('multiline.txt') as file:
... line1 = next(file)
>>> line1
'this is line 1\n'
This doesn't waste memory by reading the entire file into a list.
However, I'd say #chepner's answer would be the "prescribed" way of doing this.
Starting from your code, you can simply change the second line to
first_line = lines[0]
and you are done.
Related
When I read line by line from the file, the first line is skipped. Why does this happen and How can I solve this?
web="www.instagram.com/"
f= open("accounts.txt","r")
ft=open("add.txt", "w")
links=[]
for l in f:
name=f.readlines()
print(name)
fullweb=web+name
links.append(fullweb)
ft.writeline(fullweb)
f.close()
ft.close()
print(links)
You were starting iterating over the file f (as iterator)
for l in f:
getting the 1st line and then, immediately read all its remaining contents with f.readlines().
That makes no big sense (if not saying - no sense).
You should either do for l in f or f.readlines, not both!
with open("accounts.txt") as f:
lines = f.readlines()
...
or
with open("accounts.txt") as f:
for line in f:
...
Explanation:
With the iterator, you already iterate over the lines in the file. So it already "eats up" the first line, than you reach "readlines" readlines reads the other lines of the file. So doing both, is plainly not helpful.
I think I should have used the iteration variable instead of calling the function to readline().Anyway this solved the problem.
for l in f:
print(l)
fullweb=web+l
links.append(fullweb)
ft.writelines(fullweb)
But I don't know the theory behind how the for loop reads the file line by line without any function.
I have a text file which consists of many lines of text.
I would like to replace only the first line of a text file using python v3.6 regardless of the contents. I do not need to do a line-by-line search and replace the line accordingly. No duplication with question Search and replace a line in a file in Python
Here is my code;
import fileinput
file = open("test.txt", "r+")
file.seek(0)
file.write("My first line")
file.close()
The code works partially. If the original first line has string longer than "My first line", the excess sub-string still remains. To be clearer, if original line is "XXXXXXXXXXXXXXXXXXXXXXXXX", then the output will be "My first lineXXXXXXXXXXXXXX". I want the output to be only "My first line". Is there a better way to implement the code?
You can use the readlines and writelines to do this.
For example, I created a file called "test.txt" that contains two lines (in Out[3]). After opening the file, I can use f.readlines() to get all lines in a list of string format. Then, the only thing I need to do is to replace the first element of the string to whatever I want, and then write back.
with open("test.txt") as f:
lines = f.readlines()
lines # ['This is the first line.\n', 'This is the second line.\n']
lines[0] = "This is the line that's replaced.\n"
lines # ["This is the line that's replaced.\n", 'This is the second line.\n']
with open("test.txt", "w") as f:
f.writelines(lines)
Reading and writing content to the file is already answered by #Zhang.
I am just giving the answer for efficiency instead of reading all the lines.
Use: shutil.copyfileobj
from_file.readline() # and discard
to_file.write(replacement_line)
shutil.copyfileobj(from_file, to_file)
Reference
I am a bit new to python and I was wondering if anyone can help. Basically I am reading contents of a file and when I find the word "prb" I want to check the next line using the next() function and if it starts with the word "rt", i want to print both lines. So far I wrote this piece of code:
with open('/home/user/Desktop/3rdstep.txt', 'r') as f:
f.readline()
for line in f:
if "prb" in line:
try:
myword = next(f)
if "rt" in myword:
print(line.strip())
print(myword)
except:
print("pass")
This works fine but the only problem is that it skips randomly "rt" words for a reason I don't know. Can anyone help please or have someone done something similar?
Thanks
If your input has two consecutive lines starting with 'prb' followed by line starting with 'rt' then they are skipped. The only exception is the case where they are the first three lines in the file. This is because for line in f: reads the first line starting with 'prb' and myword = next(f) reads the second line. Thus on the following iteration line starts with 'rt'.
Instead of reading the next line you could store the previous line and then check if two lines match:
prev = ''
with open('/home/user/Desktop/3rdstep.txt') as f:
for line in f:
if prev.startswith('prb') and line.startswith('rt'):
print(prev.strip())
print(line)
prev = line
You may use if myword.startswith("rt"): instead of if "rt" in myword:
import os.path
os.path.exists('~/fileToExperiment.txt')
myfile = open('~/fileToExperiment.txt','r')
myfile.readlines()
for line in myfile:
print line
So I am trying to run this very simple python code but it doesnot output anything nor does it has any errors.
The filestoExperiment text is not empty.
Whats wrong here ? Could someone point out
By doing, myfile.readlines() you already read the entire file. Then, we you try to iterate over your file object, you already are at the end of the file.
A better practice is to do:
with open('~/fileToExperiment.txt','r') as myfile:
for line in myfile:
print line
myfile.readlines() will store the whole content of the file in memory. If you do not need the entire content at once, it is best to read line by line.
If you do need the entire content, you can use
with open('~/fileToExperiment.txt','r') as myfile:
content = myfile.read() ## or content = myfile.readlines()
Also note the use of the with statement, which is recommended when handling files (no need to close the file afterwards).
You didn't store the lines in a variable. So try this:
lines = myfile.readlines()
for line in lines:
print line
You can use either readlines() or looping file object to print or read the lines from file.
readlines() - returns the complete file as a "list of strings each separated by \n"
for example,
code:
print myfile.readlines()
output:
['Hello World\n', 'Welcome to Python\n', 'End of line\n']
Looping file object - You can loop over the file object for reading lines from a file. This is memory efficient, fast, and leads to simple code. For example,
code:
myfile = open('newfile.txt', 'r')
for line in myfile:
print line
output:
Hello World
Welcome to Python
End of line
Hello I'm making a python program that takes in a file. I want this to be set to a single string. My current code is:
with open('myfile.txt') as f:
title = f.readline().strip();
content = f.readlines();
The text file (simplified) is:
Title of Document
asdfad
adfadadf
adfadaf
adfadfad
I want to strip the title (which my program does) and then make the rest one string. Right now the output is:
['asdfad\n', 'adfadadf\n', ect...]
and I want:
asdfadadfadadf ect...
I am new to python and I have spent some time trying to figure this out but I can't find a solution that works. Any help would be appreciated!
You can do this:
with open('/tmp/test.txt') as f:
title=f.next() # strip title line
data=''.join(line.rstrip() for line in f)
Use list.pop(0) to remove the first line from content.
Then str.join(iterable). You'll also need to strip off the newlines.
content.pop(0)
done = "".join([l.strip() for l in content])
print done
Another option is to read the entire file, then remove the newlines instead of joining together:
with open('somefile') as fin:
next(fin, None) # ignore first line
one_big_string = fin.read().replace('\n', '')
If you want the rest of the file in a single chunk, just call the read() function:
with open('myfile.txt') as f:
title = f.readline().strip()
content = f.read()
This will read the file until EOF is encountered.