write specific content of a large file to multiple new file - python

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

Related

Is there any idea of deleting lines in python?

So,I have this problem,the code below will delete the 3rd line in a text file.
with open("sample.txt","r") as f:
lines = f.readlines()
del lines[2]
with open("sample.txt", "w+") as f2:
for line in lines:
f2.write(line)
How to delete all lines from a text file?
Why use loop if you want to have an empty file anyways?
f = open("sample.txt", "r+")
f.seek(0)
f.truncate()
This will empty the content without deleting the file!
I think you to need something like this
import os
def delete_line(original_file, line_number):
""" Delete a line from a file at the given line number """
is_skipped = False
current_index = 1
dummy_file = original_file + '.bak'
# Open original file in read only mode and dummy file in write mode
with open(original_file, 'r') as read_obj, open(dummy_file, 'w') as write_obj:
# Line by line copy data from original file to dummy file
for line in read_obj:
# If current line number matches the given line number then skip copying
if current_index != line_number:
write_obj.write(line)
else:
is_skipped = True
current_index += 1
# If any line is skipped then rename dummy file as original file
if is_skipped:
os.remove(original_file)
os.rename(dummy_file, original_file)
else:
os.remove(dummy_file)

How to fetch the second line data from text file in Python

How to fetch the second line data from text file in Python.
I have a text file and in file there are some data in line by line_
Dog
Cat
Cow
How to fetch the second line which is “Cat” and store in a variable in python
var = # “Cat”
You should place the text file in the same directory with your Python code, which could be the following:
with open("animals.txt", "r") as f:
animals = [line.strip() for line in f]
second_line = animals[1]
Now, the variable "second_line" contains the data you want.
You can open a file, then read line by line while counting the line number as follows:
if __name__ == '__main__':
input_path = "data/animals.txt"
var = None
with open(input_path, "r") as fin:
n_lines = 0
for line in fin:
n_lines += 1
if 2 == n_lines:
var = line.strip()
break
print(var)
Result:
Cat
If the file is big, you may avoid reading all file and use readline to read one line twice:
with open ('file.txt') as file:
line = file.readline()
line = file.readline()
print(line)
...or check 'seek' method to start reading at specific character index.

Create a new filename upon each line from a file

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

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)

Categories

Resources