Why I can't read the first line of the file? - python

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.

Related

Read first line of splitlines() file

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.

Trying to append quotes to each item in list.

I am trying to create a script that will take each line in my text file which includes one rule name in each of them. The first script I created worked (finished) but would delete everything in the file. I have been googling for past hour or so trying to take examples and apply them on my own but keep failing. The current script is as follows.
with open('TDAppendlist.txt', 'w') as file:
for line in file:
s = ('""')
seq = (file)
s.join(seq)
with open('TDAppendlist.txt') as file:
line = file.readlines()
for line in file:
line.join('"' + line + '"')
Neither of them are working. Could someone please point me in the correct direction? Thank you all for reading.
First, we'll read all the lines of the file into a list, then we can change them, and finally write them back to the file.
with open('TDAppendlist.txt') as file:
lines = list(file)
with open('TDAppendlist.txt', 'w') as file:
file.write('\n'.join(['"{}"'.format(line.rstrip('\n')) for line in lines]))
That last line can be written out to be more clear
lines = (line.rstrip('\n') for line in lines)
lines = ('"{}"'.format(line) for line in lines)
lines = '\n'.join(lines)
file.write(lines)
This produces an output file TDAppendlist_out that is just like the input, but with quotes surrounding the lines:
with open('TDAppendlist.txt', 'r') as f:
with open('TDAppendlist_out.txt', 'w') as f_out:
for line in f:
f_out.write('\"{}\"'.format(line))
This keeps the input file intact as is should you need it later, and avoids putting everything in the input file into memory all at once.

Appending characters to each line in a txt file with python

I wrote the following python code snippet to append a lower p character to each line of a txt file:
f = open('helloworld.txt','r')
for line in f:
line+='p'
print(f.read())
f.close()
However, when I execute this python program, it returns nothing but an empty blank:
zhiwei#zhiwei-Lenovo-Rescuer-15ISK:~/Documents/1001/ass5$ python3 helloworld.py
Can anyone tell me what's wrong with my codes?
Currently, you are only reading each line and not writing to the file. reopen the file in write mode and write your full string to it, like so:
newf=""
with open('helloworld.txt','r') as f:
for line in f:
newf+=line.strip()+"p\n"
f.close()
with open('helloworld.txt','w') as f:
f.write(newf)
f.close()
well, type help(f) in shell, you can get "Character and line based layer over a BufferedIOBase object, buffer."
it's meaning:if you reading first buffer,you can get content, but again. it's empty。
so like this:
with open(oldfile, 'r') as f1, open(newfile, 'w') as f2:
newline = ''
for line in f1:
newline+=line.strip()+"p\n"
f2.write(newline)
open(filePath, openMode) takes two arguments, the first one is the path to your file, the second one is the mode it will be opened it. When you use 'r' as second argument, you are actually telling Python to open it as an only reading file.
If you want to write on it, you need to open it in writing mode, using 'w' as second argument. You can find more about how to read/write files in Python in its official documentation.
If you want to read and write at the same time, you have to open the file in both reading and writing modes. You can do this simply by using 'r+' mode.
It seems that your for loop has already read the file to the end, so f.read() return empty string.
If you just need to print the lines in the file, you could move the print into for loop just like print(line). And it is better to move the f.read() before for loop:
f = open("filename", "r")
lines = f.readlines()
for line in lines:
line += "p"
print(line)
f.close()
If you need to modify the file, you need to create another file obj and open it in mode of "w", and use f.write(line) to write the modified lines into the new file.
Besides, it is more better to use with clause in python instead of open(), it is more pythonic.
with open("filename", "r") as f:
lines = f.readlines()
for line in lines:
line += "p"
print(line)
When using with clause, you have no need to close file, this is more simple.

How to update line of file in python

How to update existing line of file in Python?
Example: I want to update session.xml to sesion-config.xml without writing new line.
Input A.txt:
fix-config = session.xml
Expected output A.txt:
fix-config = session-config.xml
You can't mutate lines in a text file - you have to write an entirely new line, which, if not at the end of a file, requires rewriting all the rest.
The simplest way to do this is to store the file in a list, process it, and create a new file:
with open('A.txt') as f:
l = list(f)
with open('A.txt', 'w') as output:
for line in l:
if line.startswith('fix-config'):
output.write('fix-config = session-config.xml\n')
else:
output.write(line)
The solution #TigerhawkT3 suggested would work great for small/medium files.
For extremely large files loading the entire file into memory might not be possible, and then you would want to process each line separately.
Something along these lines should work:
import shutil
with open('A.txt') as input_file:
with open('temp.txt', 'w') as temp_file:
for l in input_file:
if l.startswith('fix-config'):
temp_file.write('fix-config = session-config.xml\n')
else:
temp_file.write(l)
shutil.move('temp.txt', 'A.txt')

Problem in Python with function only writing one line to file

I am trying to write a function in Python 3 that will write all lines that end with the string 'halloween' to a file. When I call this function, I can only get one line to write to the output file (file_2.txt). Can anyone point out where my problem is? Thanks in advance.
def parser(reader_o, infile_object, outfile_object):
for line in reader_o:
if line.endswith('halloween'):
return(line)
with open("file_1.txt", "r") as file_input:
reader = file_input.readlines()
with open("file_2.txt", "w") as file_output:
file_output.write(parser(reader))
def parser(reader_o):
for line in reader_o:
if line.rstrip().endswith('halloween'):
yield line
with open("file_1.txt", "r") as file_input:
with open("file_2.txt", "w") as file_output:
file_output.writelines(parser(file_input))
This is called a generator. It can also be written as an expression instead of a function:
with open("file_1.txt", "r") as file_input:
with open("file_2.txt", "w") as file_output:
file_output.writelines(line for line in file_input if line.rstrip().endswith('halloween'))
If you're on Python 2.7 / 3.2, you can do the two withs like this:
with open("file_1.txt", "r") as file_input, open("file_2.txt", "w") as file_output:
You don't need to do readlines() on the file, just telling the loop to iterate over the open file itself will do the exact same thing.
Your problem was that return always would exit the loop on the first match. yield stops the loop, passes out the value, then the generator can be started again from the same point.
line.endswith('halloween') might only work on the last of a file, since all other lines will have a newline appended. rstrip the line first. Also, use yield instead of return.
if line.rstrip().endswith('halloween'):
yield line
Note that this will also strip off spaces at the end of the line, which may or may not be what you want.
You'll also have to modify your consumer to
with open("file_2.txt", "w") as file_output:
for ln in parser(reader):
file_output.write(ln)
Perhaps your parser function should be a generator. At the moment it's only called once and returns the first line that has "halloween" in it.
Like the following:
def parser(reader_o):
for line in reader_o:
if line.endswith('halloween'):
yield line
with open("file_1.txt", "r") as file_input:
with open("file_2.txt", "w") as file_output:
file_output.writelines(parser(file_input))

Categories

Resources