How to add empty lines between lines in text.txt document? - python

The purpose of the code is to add an empty line between lines in text.txt document and write some words in those empty lines.
I tried looping through every line but the file should be in read mode only;
iushnaufihsnuesa
fsuhadnfuisgadnfuigasdf
asfhasndfusaugdf
suhdfnciusgenfuigsaueifcas
This is a sample of text.txt document
how can i implement this on this txt?
f = open("text.txt", 'w+')
for x in f:
f.write("\n Words between spacing")
f.close()
First i tried directly to just make a new line between each line and add couple of stuuf
I also thought of first making empty lines between each line and then add some words in the empty spaces but I didn't figure this out

Ok, for files in the region of 200 lines long you can store the whole file as a list of strings and add lines when re-writing the file:
with open("text.txt", 'r') as f:
data = [line for line in f]
with open("text.txt", 'w') as f:
for line in data:
f.write(line)
f.write("Words between spacing\n")

You can divide this operation in three steps.
In the first one, you read all the lines from the file into a list[str] using f.readlines():
with open("text.txt", "r") as f: # using "read" mode
lines = f.readlines()
Second is to join these lines inside the list using the "".join(...) function.
lines = "My line between the lines\n".join(lines)
On third step, write it down to the file:
with open("text.txt", "w") as f: # using "write" mode
f.write(lines)
Also, you can use f.read() in conjunction with text.replace("\n", ...):
with open("text.txt", "r") as f:
full_text = f.read()
full_text = full_text.replace("\n", "\nMy desirable text between the lines\n")
with open("text.txt", "w") as f:
f.write(full_text)
Initial text:
iushnaufihsnuesa
fsuhadnfuisgadnfuigasdf
asfhasndfusaugdf
suhdfnciusgenfuigsaueifcas
Final text:
iushnaufihsnuesa
My desirable text between the lines
fsuhadnfuisgadnfuigasdf
My desirable text between the lines
asfhasndfusaugdf
My desirable text between the lines
suhdfnciusgenfuigsaueifcas

Related

Trying to remove multiple space in txt file using python [duplicate]

So I have this crazy long text file made by my crawler and it for some reason added some spaces inbetween the links, like this:
https://example.com/asdf.html (note the spaces)
https://example.com/johndoe.php (again)
I want to get rid of that, but keep the new line. Keep in mind that the text file is 4.000+ lines long. I tried to do it myself but figured that I have no idea how to loop through new lines in files.
Seems like you can't directly edit a python file, so here is my suggestion:
# first get all lines from file
with open('file.txt', 'r') as f:
lines = f.readlines()
# remove spaces
lines = [line.replace(' ', '') for line in lines]
# finally, write lines in the file
with open('file.txt', 'w') as f:
f.writelines(lines)
You can open file and read line by line and remove white space -
Python 3.x:
with open('filename') as f:
for line in f:
print(line.strip())
Python 2.x:
with open('filename') as f:
for line in f:
print line.strip()
It will remove space from each line and print it.
Hope it helps!
Read text from file, remove spaces, write text to file:
with open('file.txt', 'r') as f:
txt = f.read().replace(' ', '')
with open('file.txt', 'w') as f:
f.write(txt)
In #Leonardo Chirivì's solution it's unnecessary to create a list to store file contents when a string is sufficient and more memory efficient. The .replace(' ', '') operation is only called once on the string, which is more efficient than iterating through a list performing replace for each line individually.
To avoid opening the file twice:
with open('file.txt', 'r+') as f:
txt = f.read().replace(' ', '')
f.seek(0)
f.write(txt)
f.truncate()
It would be more efficient to only open the file once. This requires moving the file pointer back to the start of the file after reading, as well as truncating any possibly remaining content left over after you write back to the file. A drawback to this solution however is that is not as easily readable.
I had something similar that I'd been dealing with.
This is what worked for me (Note: This converts from 2+ spaces into a comma, but if you read below the code block, I explain how you can get rid of ALL whitespaces):
import re
# read the file
with open('C:\\path\\to\\test_file.txt') as f:
read_file = f.read()
print(type(read_file)) # to confirm that it's a string
read_file = re.sub(r'\s{2,}', ',', read_file) # find/convert 2+ whitespace into ','
# write the file
with open('C:\\path\\to\\test_file.txt', 'w') as f:
f.writelines('read_file')
This helped me then send the updated data to a CSV, which suited my need, but it can help for you as well, so instead of converting it to a comma (','), you can convert it to an empty string (''), and then [or] use a read_file.replace(' ', '') method if you don't need any whitespaces at all.
Lets not forget about adding back the \n to go to the next row.
The complete function would be :
with open(str_path, 'r') as file :
str_lines = file.readlines()
# remove spaces
if bl_right is True:
str_lines = [line.rstrip() + '\n' for line in str_lines]
elif bl_left is True:
str_lines = [line.lstrip() + '\n' for line in str_lines]
else:
str_lines = [line.strip() + '\n' for line in str_lines]
# Write the file out again
with open(str_path, 'w') as file:
file.writelines(str_lines)

Printing the first paragraph from infile to outfile

I have one file containing a speech, and have an empty output file. I am trying to print the first paragraph of the speech (read infile) and print it out to the outfile using if/else statement.
the program isn't bugging but its not outputting to my outfile.
file = open("/Users/newuser/Desktop/MLKspeech.txt", "r")
file2 = open("/Users/newuser/Desktop/mlkparagraph.txt", "w")
content = file.read()
for j in content:
if (j == ""):
continue
elif (j == "\n"):
file2.write(content)
else:
break
Assuming paragraphs are separated by an empty line, you can iterate on the file line-by-line and write them to the new file, until an empty line is reached. An empty line can be discovered with str.isspace():
with open("MLKspeech.txt") as in_file, open("mlkparagraph.txt", 'w') as out_file:
for line in in_file:
if line.isspace():
break
out_file.write(line)
Assuming your paragraphs are separated with the '\t' character, you could try this:
with open('file1.txt', mode='rt') as file:
breakpoint = file.read().find('\t')
file.seek[0]
with open('file2.txt', mode='wt') as file2:
file2.write(file.read()[:breakpoint])
The goal is to capture the first few lines of your input file until you read an empty line (where there is either nothing or only a newline character). One way of doing that is to iterate through each line in the text with f.readlines() and store only the lines that you need in a list, breaking when you read an empty line:
content = []
with open('infile.txt') as f:
for line in f.readlines():
if line in ('', '\n'):
break
content.append(line)
You can then write each line to your output file:
with open('outfile.txt', 'w') as f:
for line in content:
f.write(line)

reading .txt file in python

I have a problem with a code in python. I want to read a .txt file. I use the code:
f = open('test.txt', 'r') # We need to re-open the file
data = f.read()
print(data)
I would like to read ONLY the first line from this .txt file. I use
f = open('test.txt', 'r') # We need to re-open the file
data = f.readline(1)
print(data)
But I am seeing that in screen only the first letter of the line is showing.
Could you help me in order to read all the letters of the line ? (I mean to read whole the line of the .txt file)
with open("file.txt") as f:
print(f.readline())
This will open the file using with context block (which will close the file automatically when we are done with it), and read the first line, this will be the same as:
f = open(“file.txt”)
print(f.readline())
f.close()
Your attempt with f.readline(1) won’t work because it the argument is meant for how many characters to print in the file, therefore it will only print the first character.
Second method:
with open("file.txt") as f:
print(f.readlines()[0])
Or you could also do the above which will get a list of lines and print only the first line.
To read the fifth line, use
with open("file.txt") as f:
print(f.readlines()[4])
Or:
with open("file.txt") as f:
lines = []
lines += f.readline()
lines += f.readline()
lines += f.readline()
lines += f.readline()
lines += f.readline()
print(lines[-1])
The -1 represents the last item of the list
Learn more:
with statement
files in python
readline method
Your first try is almost there, you should have done the following:
f = open('my_file.txt', 'r')
line = f.readline()
print(line)
f.close()
A safer approach to read file is:
with open('my_file.txt', 'r') as f:
print(f.readline())
Both ways will print only the first line.
Your error was that you passed 1 to readline which means you want to read size of 1, which is only a single character. please refer to https://www.w3schools.com/python/ref_file_readline.asp
I tried this and it works, after your suggestions:
f = open('test.txt', 'r')
data = f.readlines()[1]
print(data)
Use with open(...) instead:
with open("test.txt") as file:
line = file.readline()
print(line)
Keep f.readline() without parameters.
It will return you first line as a string and move cursor to second line.
Next time you use f.readline() it will return second line and move cursor to the next, etc...

How to update a specific line in a file in python?

I am trying to create a program which can update a file.
I created a test program as I cannot figure out how to update a part of the file.
I want to make it so that if a name matches that of one in the file, it will delete the one name and its data and place the name and new data at the end.
Here is my code where I am simply trying to remove the name from the list:
lines = open("input.txt", "rt")
output = open("output.txt", "wt")
for line in lines:
if not "Ben":
output.write(line+"\n")
lines.close()
output.close()
looks like you just need to fix your condition:
lines = open("input.txt", "rt")
output = open("output.txt", "wt")
for line in lines:
if "Ben" not in line:
output.write(line+"\n")
lines.close()
output.close()
lines = open("input.txt", "rt")
output = open("output.txt", "wt")
for line in lines:
if not "Ben" in line:
output.write(line+"\n")
else:
output.write(line.replace("Ben","replace/delete Ben")+"\n")
lines.close()
output.close()

Removing all spaces in text file with Python 3.x

So I have this crazy long text file made by my crawler and it for some reason added some spaces inbetween the links, like this:
https://example.com/asdf.html (note the spaces)
https://example.com/johndoe.php (again)
I want to get rid of that, but keep the new line. Keep in mind that the text file is 4.000+ lines long. I tried to do it myself but figured that I have no idea how to loop through new lines in files.
Seems like you can't directly edit a python file, so here is my suggestion:
# first get all lines from file
with open('file.txt', 'r') as f:
lines = f.readlines()
# remove spaces
lines = [line.replace(' ', '') for line in lines]
# finally, write lines in the file
with open('file.txt', 'w') as f:
f.writelines(lines)
You can open file and read line by line and remove white space -
Python 3.x:
with open('filename') as f:
for line in f:
print(line.strip())
Python 2.x:
with open('filename') as f:
for line in f:
print line.strip()
It will remove space from each line and print it.
Hope it helps!
Read text from file, remove spaces, write text to file:
with open('file.txt', 'r') as f:
txt = f.read().replace(' ', '')
with open('file.txt', 'w') as f:
f.write(txt)
In #Leonardo Chirivì's solution it's unnecessary to create a list to store file contents when a string is sufficient and more memory efficient. The .replace(' ', '') operation is only called once on the string, which is more efficient than iterating through a list performing replace for each line individually.
To avoid opening the file twice:
with open('file.txt', 'r+') as f:
txt = f.read().replace(' ', '')
f.seek(0)
f.write(txt)
f.truncate()
It would be more efficient to only open the file once. This requires moving the file pointer back to the start of the file after reading, as well as truncating any possibly remaining content left over after you write back to the file. A drawback to this solution however is that is not as easily readable.
I had something similar that I'd been dealing with.
This is what worked for me (Note: This converts from 2+ spaces into a comma, but if you read below the code block, I explain how you can get rid of ALL whitespaces):
import re
# read the file
with open('C:\\path\\to\\test_file.txt') as f:
read_file = f.read()
print(type(read_file)) # to confirm that it's a string
read_file = re.sub(r'\s{2,}', ',', read_file) # find/convert 2+ whitespace into ','
# write the file
with open('C:\\path\\to\\test_file.txt', 'w') as f:
f.writelines('read_file')
This helped me then send the updated data to a CSV, which suited my need, but it can help for you as well, so instead of converting it to a comma (','), you can convert it to an empty string (''), and then [or] use a read_file.replace(' ', '') method if you don't need any whitespaces at all.
Lets not forget about adding back the \n to go to the next row.
The complete function would be :
with open(str_path, 'r') as file :
str_lines = file.readlines()
# remove spaces
if bl_right is True:
str_lines = [line.rstrip() + '\n' for line in str_lines]
elif bl_left is True:
str_lines = [line.lstrip() + '\n' for line in str_lines]
else:
str_lines = [line.strip() + '\n' for line in str_lines]
# Write the file out again
with open(str_path, 'w') as file:
file.writelines(str_lines)

Categories

Resources