Reading each line from text file - python-3.x

I have a script which reads each line from text file. but somehow it prints all at once. I want to run one line end and run next. here is the code.
f = open('textfile.txt', 'r')
file= f.read()
for x in file:
print(x, file.strip())
comSerialPort.write(x.encode('utf-8'))

Use readlines instead of read
with open('textfile.txt', 'r') as f:
lines = f.readlines()
for line in lines:
print(line)
# do stuff with each line

Use with statement and then iterate lines.
Ex:
with open('textfile.txt', 'r') as infile:
for line in infile:
print(line)
comSerialPort.write(line.strip().encode('utf-8'))
Note: read() reads the entire content of the file.

Related

How to Read ' n ' line from a text file and store it to another text file in python

I have a text file as "file_in.txt".I want read the first three lines from that
file and Write the those three lines read from "file_in.txt" to a new file
called "file_out.txt".
After write it, read "file_out.txt" and Print it's contents
file_in = "file_in.txt"
file_out = "file_out.txt"
data = ""
# read the first 3 lines of file_in.txt
with open(file_in, 'r') as f:
for i in range(3):
data += f.readline()
# write to file_out.txt
with open(file_out, 'w') as f:
f.write(data)
# read the content of file_out.txt
with open(file_out, 'r') as f:
content = f.read()
print(content)

Delete multiple line in a text file but it is deleting only last line

def delet_line(exp_res):
filename = "C:\\Users\\beher\\Desktop\\my.txt"
exp_res_sl = exp_res.splitlines()
#print('file name is ',filename)
with open(filename, "r") as f:
lines = f.readlines()
for expres_line in exp_res_sl:
print(expres_line)
with open(filename, "w") as f:
for line in lines:
if line.strip("\n") != expres_line:
f.write(line)
delet_line("Mohan\nmohan")
Here i am trying to delete the a multiline string passing as argument but it deletes only the last line of the passing argument pls help| thanks in advance.
Maybe like so:
def delete_line(skip_lines):
filename="C:\\Users\\beher\\Desktop\\my.txt"
with open(filename, "rt") as f:
lines = f.readlines()
with open(filename, "wt") as f:
for line in lines:
if line.strip('\n') not in skip_lines:
f.write(line)
delete_line(['Mohan', 'mohan'])

Python: input saving multiline string

while True:
try:
line = input("paste:")
except EOFError:
break
f = open("notam_new.txt", "w+")
f.write(line)
f.close()
This code return only the last line of multi-line after Ctrl+D
I tried also:
notam = input("paste new notam: ")
f = open("notam_new.txt", "w+")
f.write(notam)
f.close()
getting only the first row.
Any ideas?
You're setting line in a loop, so every iteration you're just overwriting said line with the next one You need to accumulate your lines in a list (created before the while True) so you can keep track of all of them, and then write to the file in a loop. Plus you also need to add a newline as input() strips it.
lines = []
while True:
try:
lines.append(input("paste:"))
except EOFError:
break
with open("notam_new.txt", "w+") as f:
for line in lines:
f.write(line)
f.write('\n')

append content of text file to other python

I'm a "basic" python user and I'm trying to do following:
There is a file "input.txt" which is created each 5 minutes with different content. Now I'm just trying,each time the file is generated, to copy (or better to say to append) the whole content to an file "output.txt":
with open("input.txt",'r') as f:
lines = f.readlines()
with open("output.txt", "a") as f1:
f1.writelines("lines\n")
f1.write("--This-is-just-a-line-to-differ-the-content-blocks")
Now, I'm able to copy the content, but the file "output.txt" is each time overwritten. What I'm doing wrong?
That happened because you are writing the output file, not the input file
with open("file.txt",'r') as f:
lines = f.readlines()
with open("output.txt", "w") as f1:
f1.writelines(lines)
f1.write("--This-is-just-a-line-to-differ-the-content-blocks")
f.close()
f1.close()
So it worked with:
with open("file.txt",'r') as f:
lines = f.readlines()
with open("output.txt", "a") as f1:
f1.writelines(lines)
f1.write("--This-is-just-a-line-to-differ-the-content-blocks")
f.close()
f1.close()
#Reinier Hernández Ávila: Thx for the tipp with f.close(). But in this case the overwriting argument "a" worked and not the "w".

Python-2.7 write to file

I have this script:
f = open("/ggg/darr/file/", "r+")
a = 0
for line in f:
if a ==58:
print (line)
line1 = "google.ca"
f.write(line1)
print line
a = a+1
f.close()
I want to keep my file but only to change what is written on line 58 to "google.ca"
then save it
using linux: mint-17.2
# Read data from file
with open('yourfile.txt', 'r') as file:
# read all line in the file to data array
data = file.readlines()
# change data on line 58 (array start from 0)
data[57] = 'Data you need to change'
# Write data back
with open('yourfile.txt', 'w') as file:
file.writelines(data)
You need to decide whether you want to write a new file (with print) or change the old file (with r+ mode and f.write). You will probably be happiest if you write a new file.
dataRead = []
f = open("/ggg/darr/file/", "r+")
a = 0
for line in f:
if a == 58:
line = "google.ca"
dataRead.append(line)
a = a+1
f.close()
f2 = open("/some/new/file","w")
for line in dataRead:
f2.write(line)
f2.close()
With the answer of Adisak Anusornsrirung I wrote it like this:
with open('sss.txt','r') as file:
data = file.readlines()
print (data[14])
file.close()
data[14] = "some data here"+"\n"
with open ("sss.txt", 'w') as file:
file.writelines(data)
file.close()
f = open("sss.txt", 'r')
print (f.read())
f.close()

Resources