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)
Related
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])
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")
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)
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")
def createOutfile(text,lines,outfile):
infile = open(text, 'r')
newtext = open(outfile, 'w')
count = 0
newfile = ''
for line in infile:
count = count + 1
newfile = newfile + "{0}: {1}".format(count,line)
newtext.write(newfile)
print(newtext)
I'm trying to take a file (text) and create a copy of that file (outfile) that just numbers the lines. The code i have now doesn't print an error but it gives me this:
<_io.TextIOWrapper name='mydata.out' mode='w' encoding='UTF-8'>
If i replace print(newtext) with print(newfile) it gives me exactly what i want. What am i doing wrong?
To read a file's content you need to use its .read() method:
newtext.seek(0) #Move the file pointer to the start of the file.
print(newtext.read())
You can open the output file in read-write mode,
def number_lines(old_file_name, new_file_name, fmt="{}: {}"):
with open(old_file_name) as inf, open(new_file_name, "w+") as outf:
for i,line in enumerate(inf, 1):
outf.write(fmt.format(i, line))
# show contents of output file
outf.seek(0) # return to start of file
print(outf.read())
or just print each line as it is written:
def number_lines(old_file_name, new_file_name, fmt="{}: {}"):
with open(old_file_name) as inf, open(new_file_name, "w+") as outf:
for i,line in enumerate(inf, 1):
numbered = fmt.format(i, line)
outf.write(numbered)
print(numbered.rstrip())
What you are doing is:
line 3: newtext contains the file descriptor of your output file.
line 5-8: newfile contains the text you want to output.
line 10: you print your file descriptor (newtext) and the outputed text (newfile).
At line 10, when you print the file descriptor (newtext), python displays the representation of this file descriptor:
the class name: TextIOWrapper
the name of you file: mydata.out
the opening mode: w
and the encoding: UTF-8
And when you print newfile, it displays the string you created just before.
If you want to read your file after writing in it, you need to open it in read/write mode: "w+":
>>> f = open("File", "w+") # open in read/write mode
>>> f.write("test") # write some stuff
>>> # the virtual cursor is after the fourth character.
>>> f.seek(0) # move the virtual cursor in the begining of the file
>>> f.read(4) # read the data you previously wrote.
'test'