fh=open('Spam.mbox',encoding='utf-8')
data=fh.read()
for line in data:
print(line)
When I execute the above code, python prints out the data one character at a time instead of line by line.
Please advise.
you can do that using the readlines() function.
with open('Spam.mbox',encoding='utf-8') as f:
data = f.readlines()
With the data variable you can iterate over it and print each line
for i in data:
print(i)
When reading files use the with statement because then the file will be closed after it has been processed.
Read line by line:
with open("textfile.txt", "r") as f:
for line in f:
print(line)
Read all the lines and then loop through the line:
with open("textfile.txt", "r") as f2:
lines = f2.readlines()
for ln in lines:
print(ln)
Related
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)
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...
I am writing code to generate words from one file to another
I have done all ok but the problem that when I use line it feed a new line in the output file I want to next word after line to be written at the same line
the code
with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write("<answer>" + line +"doit");
now doit comes in a new line in the out.txt
the text file has 3 lines
door
window
house
The problem is that your variable line contains a \n at the end, which you have to remove yourself:
with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write("<answer>" + line[:-1] +"doit")
The problem of using rstrip as the other answer suggests is that you would lose ending spaces: ' aa \n'.rstrip() gives you ' aa'. This might or might not be what you need.
Use rstrip() to remove the trailing \n
with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write("<answer>" + line.rstrip('\n') +"doit");
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()
I want to split a text file in python, using the following peice of code:
inputfile = open(sys.argv[1]).read()
for line in inputfile.strip().split("\n"):
print line
the problem is, that it's read the first 12 lines only!! the file is large more than 10 thousand lines!
What is the possible reason!
Thanks,
with open(sys.argv[1]) as inputfile:
for line in inputfile:
print(line)
Use readlines() which will generate list automatically and no need to read by "\n".
Try this:
text = r"C:\Users\Desktop\Test\Text.txt"
oFile = open(text, 'r')
line = oFile.readline()[:-1]
while line:
splitLine = line.split(' ')
print splitLine
line = oFile.readline()[:-1]
oFile.close()
I use this style to iterate through huge text files at work