Python-2.7 write to file - linux

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()

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)

Reading each line from text file

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.

Running a Python script for files in a folder

There are 15 text files in a folder and I am trying to extract certain parts of each file and output them to a new file.
I am able to extract each file individually by just changing the file name and append each file to the output file but this means copying the same code 15 times and just changing the file name each time.
import glob,os
lst = []
filelist=glob.glob ('/C:/Users/bridaly/Documents/PythonTest/Python_Test_ENdata_3080_v20150914/input/*')
for file in filelist:
if os.path.isfile(file):
for line in filelist:
line = line.strip()
if not (
line.startswith("APPEND") or line.startswith("_") or
line.startswith("SAP") or line.startswith("~") or
line.startswith("INCLUDE") or line.startswith("ABAP")
or line.strip() == "" or line.startswith("Field") or
line.startswith("Short")
) :
y=line.replace(' ',' ')
#print(y)
z = y.replace('X','')
#print(z)
w = "|".join(z.split())
#print(w)
x = w.split("|",3)[:4]
#print(x)
x.insert(0,'./input/01BKPF')
#print(x)
if len(x) >=4:
t = [s.replace('|',' ') for s in x]
#print(t)
print("|".join(t))
lst.append("|".join(t))
#Output Script
output_file = open('Output_Final.txt', 'w')
for l in lst:
output_file.write(l)
output_file.write('\n')
output_file.close()
"""
The output should extract what's written in the code but for each file and append it to the output file. I have gotten the correct output by copying the code 15 times but I just want to use it once as it is more efficient.
files = glob.glob('path')
for file in files:
file_name = os.path.basename(file)
print(file_name)
you can iterate for each file

Add new line to a file after matching pattern - Python

I have a file called 'file.txt' and its contents are as below.
[Jack]
sv0f3fj3jff0j
[Tom]
343767y6y6y5yu
I have to add new line just after each names(by reading the user name as input). Can any one please help me ? I have tried using the below steps but didn't succeeded.
#!/usr/bin/python36
inv_file = '/root/file.txt'
cn_search = input("\nEnter the name: ")
new_line = input("\nEnter the new line : ")
with open(inv_file) as in_file:
buf = in_file.readlines()
print(buf.replace('[').replace(']'))
with open(inv_file, "w") as in_file:
for line in buf:
if line.startswith('[') and line.endswith(']'):
mod_line = line.replace('[', '').replace(']', '')
if mod_line == cn_search:
buf = buf + "\n" + new_ip_ex
out_file.write(buf)
It is correct to read and then rewrite the file, but you're also changing the brackets which is unnecessary. Do it like this:
import re
with open(inv_file) as in_file:
old_contents = in_file.readlines()
with open(inv_file, 'w') as in_file:
for line in old_contents:
in_file.write(line)
if re.search(r'\[.*\]', line):
in_file.write('YOUR MESSAGE HERE\n')

Deleting a line from txt file

I have a txt file with lists of names like this
Name1
Name2
Name3
I want to delete the line with "Name2" in it, if Name2 is in the list. I got this code:
f = open(list,'r')
if("Name2" in f.read().splitlines()):
lines = f.readlines()
f.close()
f = open(badhumanslist, "w")
for line in lines:
if line != "Name2" + "\n":
f.write(line)
f.close()
The problem is that this code empties the whole file. I don't see my error, it should rewrite all the lines, except the one with "Name2"
You already read the whole file in line 2: f.read(). Then, lines = f.readlines() returns an empty list.
def read_all():
with open(filename, "r") as file:
return file.read()
content = read_all()
lines = content.splitlines()
if "Name2\n" in lines:
with open(filename, "w") as file:
for line in lines:
if line != "Name2\n":
file.write(line)

Resources