i need to use
for line in doc.split('\n'):
and do some operation on each line but i got at the end of the file
empty line as i think it split a new line every time ! how can i avoid this problem ?
Please rephrase your question, since it is not very clear.
Anyway, if you are working with a text file you can just use:
with open("path_to_soruce_textfile", "r") as src, open("path_to_dest_textfile", "w") as dst:
for line in src.readlines(): # this gives you a list of lines with each line finishing with \n
processed_line = modidy(line)
dst.write(processed_line) # make sure \n is at the end of each line when you write
# the file is automatically closed
Related
Let me try to lay this out. I have a text file, each line of the text file is a different string. My trouble is if I want to grab line 3. When I try to use file.readline(3) or file.read(3) I will get the first 3 characters of the first line of the text file instead of all of line 3. I also tried file.readlines(3) but that just returned ['one\n'] which happens to yet again be the first line with [' \n'] around it. I am having more trouble with this that I already should be but I just gave up and need help. I am doing all of this through a discord bot if that helps, though that shouldn't be affecting this.
as what Barmar said use the file.readlines(). file.readlines makes a list of lines so use an index for the line you want to read. keep in mind that the first line is 0 not 1 so to store the third line of a text document in a variable would be line = file.readlines()[2].
edit: also if what copperfield said is your situation you can do:
def read_line_from_file(file_name, line_number):
with open(file_name, 'r') as fil:
for line_no, line in enumerate(fil):
if line_no == line_number:
file.close()
return line
else:
file.close()
raise ValueError('line %s does not exist in file %s' % (line_number, file_name))
line = read_line_from_file('file.txt', 2)
print(line)
if os.path.isfile('file.txt'):
os.remove('file.txt')
it's a more readable function so you can disassemble it to your liking
unfortunately you just can't go to a particular line in a file in a simple easy way, you need iterate over the file until you get to the desire line or know exactly where this line start withing the file and seek it and then read one line from it
for the first you can do:
def getline(filepath,n):
with open(filepath) as file:
for i,line in enumerate(file):
if i == n:
return line
return ""
Of course you can do file.readlines()[2] but that read ALL the file and put ALL its lines it into a list first, which can be a problem if the file is big
For the other option check this answer here
I am trying to use line.replace such that I can replace two separate variables in the same line before moving onto the next line.
lets say the text file "file.txt' is:
(1.00)
(2.00)
(3.00)
I would like to replace the ( and ) with and empty space for each line. Here is what I have.
file=open('file.txt', 'r')
file_1=open('file_1.txt', 'w')
for line in file:
x=line.replace('(', "")
file_1.writelines(x)
file_2=open('file_1.txt', 'r')
file_3=open('file_2.txt', 'w')
for line in file_2:
y=line.replace(')', "")
file_3.writelines(y)
Is there a way to make this more efficient?
Thank you for your help,
Kyle
You just need to call the replace function a second time after you do it the first time:
for line in file:
x=line.replace('(', "")
x=x.replace(')', "")
file_1.writelines(x)
Or, you could even call the replace function twice on the same line:
for line in file:
x=line.replace('(', "").replace(')', "")
file_1.writelines(x)
You can make this much simpler. As others have said, you can call replace twice, because it does return a string, so you could do...
for line in file:
x=line.replace('(', "").replace(')', "")
file_1.writelines(x)
You don't actually need the x either, so you can combine them into one line. The works because the replace function keeps returning a string.
for line in file:
file_1.writelines(line.replace('(', "").replace(')', ""))
And now that it's a one line for loop, we can make this even simpler into a list comprehension. Making the entire program
file=open('file.txt', 'r')
file_1=open('file_1.txt', 'w')
[file_1.writelines(line.replace('(', "").replace(')', "")) for line in file]
Don't hesitate to ask questions.
This question already has answers here:
How to read a file line-by-line into a list?
(28 answers)
Closed 5 years ago.
In order to extract some values from this file :
I need to read it line by line.
I tried to read line by line first but i don't know why it doesn't work.
I tried this :
#! /usr/bin/python
file = open('/home/results/err.txt')
for line in file.readline():
print line
EDIT:
Problem: working but not showing this lines (this is the file)
Just the last line of them which is: (this is what is generated)
You need to iterate through the file rather than the line:
#! /usr/bin/python
file = open('/home/results/err.txt')
for line in file:
print line
file.readline() only reads the first line. When you iterate over it, you are iterating over the characters in the line.
file.readline() already reads one line. Iterating over that line gives you the individual characters.
Instead, use:
for line in file:
…
Try this :
#! /usr/bin/python
file = open('/home/results/err.txt')
for line in file.readlines():
print line
You might want to use a context manager with that to automatically close your opened file after the lines have been read, that is to ensure nothing unexpected happens to your file while python is processing it.
with open('/home/results/err.txt', 'r') as file:
for line in file:
print line
readline() would read your file line-by-line but iterating over that would print the letters individually.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Editing specific line in text file in python
I am writing a software that allows users to write data into a text file. However, I am not sure how to delete the first line of the text file and rewrite the line. I want the user to be able to update the text file's first line by clicking on a button and inputing in something but that requires deleting and writing a new line as the first line which I am not sure how to implement. Any help would be appreciated.
Edit:
So I sought out the first line of the file and tried to write another line but that doesn't delete the previous line.
file.seek(0)
file.write("This is the new first line \n")
You did not describe how you opened the file to begin with. If you used file = open(somename, "a") that file will not be truncated but new data is written at the end (even after a seek on most if not all modern systems). You would have to open the file with "r+")
But your example assumes that the line you write is exactly the same length as what the user typed. There is no line organisation in the files, just bytes, some of which indicate line ending.
Wat you need to do is use a temporary file or a temporary buffer in memory for all the lines and then write the lines out with the first replaced.
If things fit in memory (which I assume since few users are going to type so much it does not fit), you should be able to do:
lines = open(somename, 'r').readlines()
lines[0] = "This is the new first line \n"
file = open(somename, 'w')
for line in lines:
file.write(line)
file.close()
You could use readlines to get an array of lines and then use del on the first index of the array. This might help. http://www.daniweb.com/software-development/python/threads/68765/how-to-remove-a-number-of-lines-from-a-text-file-
I have a text file with almost a thousand lines such as:
WorldNews,Current
WorldNews,Current,WorldNews#here',
'WorldNewsPro#here Zebra,Poacher',
'Dock,DS_URLs#here'
Zebra,Poacher,ZebraPoacher#here
Zebra,Dock,ZebraDock#here
Timer33,Timer33#here
Sometimes the line ends without "#here" sometimes it ends with "#here" sometimes it has "#here" in the middle of the line and sometimes the line ends with "#here'"
I want to strip all the lines that do NOT have "#here" in them at all. I tried RegEx:
> (^(#here$))
> [\W](#here)
etc. with no luck.
How should I pull the lines with "#here" so my new file (or the output) has only:
WorldNews,Current,WorldNews#here',
'WorldNewsProfessional52#here
Zebra,Poacher',
'DocuShare,AC_DS_URLs#here'
Zebra,Poacher,ZebraPoacher#here
Zebra,DocuShare,ZebraDocushare#here
XNTimer,XNTimer#here
I was thinking it should read the whole line from start to end and if it has #here anywhere in the line, print it. If not, ignore and read the next line.
Thanks,
Adrian
Maybe this helps: (assuming filename is the name of your input file)
with open(filename) as stream:
for line in stream:
if '#here' in line:
print line
You dont need regex. You can use a string methods to do such simple filtering:
def hasstr( lines, s ):
# a generator expression can filter out the lines
return (line for line in lines if s in line)
# get all lines in the file with #here in them
filtered = hasstr(open(the_file, 'rt'), '#here')
You want the in operator.
for line in sys.stdin:
if '#here' in line:
sys.stdout.write(line)