Create a new filename upon each line from a file - python

I could open the file "setup.conf", replace the text from "Hostname=server" to "Hostname=server2" and save it as "setup2.conf".
But, I want that each line from "list.txt" becomes the name of the new file, instead of "setup2.conf".
Content of "list.txt":
server1
server2
server3
For example of what I did to read each line:
fh = open('list.txt')
while True:
line = fh.readline()
print(line)
if not line:
break
fh.close()
Sample of what I did to replace a text and save the file:
fin = open("setup.conf", "rt")
fout = open("setup2.conf", "wt")
for line in fin:
fout.write(line.replace('Hostname=server1', 'Hostname=server2'))
fin.close()
fout.close()

Open a new file for each read line, then write to it. For example
with open('list.txt') as fh:
for line in fh:
server = line.rstrip()
with open(server + ".conf", "w") as fout, open("setup.conf") as setup:
for line in setup:
fout.write(line.replace("Hostname=server1", "Hostname=" + server)
fout.write("\n")

Related

write specific content of a large file to multiple new file

I have a large txt file in format:
bbox_003266.txt
172.56 96.36 199.61 295.15
922.0 79.9 1242.0 349.52
378.56 128.58 803.91 234.82
701.14 176.7 862.34 285.47
bbox_003200.txt
705.95 117.81 1242.0 252.43
1036.12 183.52 1242.0 375.0
124.11 143.43 296.91 230.32
0.0 6.6 112.99 375.0
0.0 186.66 14.82 375.0
for each line beginning with bbox, I want to write the content below that to a new file with the same name as the bbox. i.e in file above, I want to have two files with names: bbox_003266.txt and bbox_003200.txt.
I have tried this:
file_in = 'final.txt'
counter = 3199
with open(file_in, 'r') as fin:
line = fin.readline() # read file in line by line
while line:
if 'bbox' in line:
try:
fout.close() # close the old file
except:
pass
# augment the counter and open a new file
counter += 1
fout = open('' % counter, 'w')
fout.write(line) # write the line to the output file
line = fin.readline() # read the next line of the input file
fout.close() # close the last output file
Your approach is right, just fixed some logical bugs and your code is working fine
file_in = 'final.txt'
fout = None
with open(file_in, 'r') as fin:
line = fin.readline() # read file in line by line
while line:
if 'bbox' in line:
try:
if fout is not None:
fout.close() # close the old file
except:
pass
fout = open(line.strip(), 'w')
print('New file created', line.strip())
else:
fout.write(line) # write the line to the output file
line = fin.readline() # read the next line of the input file
fout.close() # close the last output file

Fetching a line which comes 2 lines after searched line from a text file in python

Text file contains below data:
InitialSearch='Searched data'
file = open("textfile.txt","r")
lines = file.readlines()
file.close()
fileOutput = open ('NewTextFile.txt', 'w')
for x,line in enumerate(lines):
if line.find(InitialSearch)>=0:
fileOutput.write(line)
fileOutput.close
Code is not properly working
You already have the index of the "matched" line in your for loop. Just add two to it, and you will have the row you want to add to the output file.
InitialSearch='Searched data'
file = open("textfile.txt","r")
lines = file.readlines()
file.close()
with open('NewTextFile.txt', 'w') as fileOutput
for x,line in enumerate(lines):
if line.find(InitialSearch)>=0:
fileOutput.write(lines[x+2])

Append String to each line of .txt file in python?

I want to append some text to every line in my file
Here is my code
filepath = 'hole.txt'
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
#..........
#want to append text "#" in every line by reading line by line
text from .txt file
line = fp.readline()
cnt += 1
You can read the lines and put them in a list. Then you open the same file with write mode and write each line with the string you want to append.
filepath = "hole.txt"
with open(filepath) as fp:
lines = fp.read().splitlines()
with open(filepath, "w") as fp:
for line in lines:
print(line + "#", file=fp)
Assuming you can load the full text in memory, you could open the file, split by row and for each row append the '#'. Then save :-) :
with open(filepath, 'r') as f: # load file
lines = f.read().splitlines() # read lines
with open('new_file.txt', 'w') as f:
f.write('\n'.join([line + '#' for line in lines])) # write lines with '#' appended
I'll assume the file is small enough to keep two copies of it in memory:
filepath = 'hole.txt'
with open(filepath, 'r') as f:
original_lines = f.readlines()
new_lines = [line.strip() + "#\n" for line in original_lines]
with open(filepath, 'w') as f:
f.writelines(new_lines)
First, we open the file and read all lines into a list. Then, a new list is generated by strip()ing the line terminators from each line, adding some additional text and a new line terminator after it.
Then, the last line overwrites the file with the new, modified lines.
does this help?
inputFile = "path-to-input-file/a.txt"
outputFile = "path-to-output-file/b.txt"
stringToAPpend = "#"
with open(inputFile, 'r') as inFile, open(outputFile, 'w') as outFile:
for line in inFile:
outFile.write(stringToAPpend+line)

Catch links from a txt file

I have a file txt, where there are severals lines... Some of these are links. My question is: How can I catch all this links and save them on another txt file? I'm a newbie.
I tried with this but it doesn't work:
filee = open("myfile.txt").readlines()
out_file = open("out.txt","w")
out_file.write("")
out_file.close()
for x in filee:
if x.startswith("http"):
out_file.write(x)
print (x)
You can't write to a closed file. Just move the out_file.close() at the end of your code:
filee = open("myfile.txt").readlines()
out_file = open("out.txt","w")
out_file.write("")
for x in filee:
if x.startswith("http"):
out_file.write(x)
print (x)
out_file.close()
Here a cleaner version:
# open the input file (with auto close)
with open("myfile.txt") as input_file:
# open the output file (with auto close)
with open("out.txt", "w") as output_file:
# for each line of the file
for line in input_file:
# append the line to the output file if start with "http"
if line.startswith("http"):
output_file.write(line)
You can also combine the two with:
# open the input/output files (with auto close)
with open("myfile.txt") as input_file, open("out.txt", "w") as output_file:
# for each line of the file
for line in input_file:
# append the line to the output file if start with "http"
if line.startswith("http"):
output_file.write(line)

Replacing multiple words in a text file and writing new text to output file

I am trying to write a function which takes a text file as input file and create an output file with the same text with words replaced. This function will edit Emma with George, she with he and her with his.
My code is:
switch = {"Emma":"George", "she":"he", "hers":"his"}
def editWords(fin):
#open the file
fin = open(filename, "r")
#create output file
with open("Edited.txt", "w") as fout:
#loop through file
for line in fin.readlines():
for word in switch.keys():
if word in line.split():
line = line.replace(word, switch[word])
fout.write(line)
fin.close()
The out put file is created however blank.
Does anyone know how to get the output file with the edited text?
You never write the file.
You use i in two loops
You never close the infile
You don't respect the newlines
...
Here an example that works
switch = {"Emma":"George", "she":"he", "hers":"his"}
def editWords(filename):
#open the file
fin = open(filename, "r")
#create output file
with open("/tmp/Edited", "w") as fout:
#loop through file
for line in fin.readlines():
for word in switch.keys():
if word in line.split():
line = line.replace(word, switch[word])
fout.write(line)
fin.close()
editWords("/tmp/filename")

Categories

Resources