In Python I'd like to open a text file as file, and copy only part of the file to a new file. For example, I want to copy only part of the file, say between the line EXAMPLE\n and line END\n. So I want to delete everything before line EXAMPLE\n and everything after line END\n. How can I do that?
I can read the file using the following code, but how do I delete the
with open(r'filepath\myfile.txt', 'r') as f:
file = f.readlines()
<delete unwanted lines in file>
with open(r'filepath\newfile.txt', 'r') as f:
f.writelines(file)
Create a new array and only add the lines you want to that array:
new_lines = []
found_example=False
found_end=False
for line in file:
if line == "EXAMPLE\n": found_example=True
if line == "END\n": found_end=True
if found_example != found_end: new_lines.append(line)
file = new_lines
Now just write file to your file and you are done. Note that in your example you didn't open the file in write mode, so it would look more like this:
with open(r'filepath\newfile.txt', 'w+') as f:
f.writelines(file)
Read each line and notice whether it contains EXAMPLE or END. In the former case, set a flag to start outputting lines; in the latter, set the same flag to stop.
process = False
with open('myfile.txt') as f, open('newfile.txt', 'w') as g:
for line in f:
if line == 'EXAMPLE\n':
process = True
elif line == 'END\n':
process = False
else:
pass
if process:
line = line.strip()
print (line, file=g)
Related
(I have only been learning Python3 for about 2 weeks now. So if you could keep the answer as ELI5 as possible that would be great)
In this image, I have first read the file and then second zeroed the file and recreated it while removing all the lines containing 'Ford'
This image shows the contents of the file that I wish to be printed out
The problem I have is that the result is being printed as 'none'.
How would I make it so this program prints out what is inside the file?
Thanks!
code below
def delete_ford(path, term):
buffer = []
with open(path, "r") as file:
for line in file:
buffer.append(line.strip())
with open(path, "w") as file:
for line in buffer:
if line != term:
file.write(line + "\n")
with open(path, "r") as file:
for line in file:
buffer.append(line.strip())
print(buffer)
print(delete_ford("cars.txt", "Ford"))
As #John Zwinck and #Albert Alberto pointed out, your function has nothing to return as the output is written to the file.
If you want it simply to print out the contents of the file, you can do this when you're writing to it like this:
with open(path, "w") as file:
for line in buffer:
if line != term:
file.write(line + "\n") # This is what is being written to the file
print(line) # So this will effectively output the contents of the file
Hope this does what you want it to
I have a text file with file paths:
path1
path2
path3
...
path100000000
I have my python script app.py that should run on each file (path1, path2 ...)
Please advise what is the best way to do it?
Should I just get it as argument, and then:
with open(input_file, "r") as f:
lines = f.readlines()
for line in lines:
main_function(line)
Yes that should work, except readlines() doesn't remove newline characters.
with open(input_file, "r") as f:
lines = f.readlines()
for line in lines:
main_function(line.strip())
**Note: The above code assumes the file is in the same directory as the python script file.
You are using context managers. Hence, place the code inside the context.
So according to your comment,
If you want to pass filename where you will read the file contents in the main_function, then the above code will work.
If you want to read the file and then pass the file contents, then you will have to modify the above code to first read the content and then pass it to the function
with open(input_file, "r") as f:
lines = f.readlines()
for line in lines:
main_function(open(line.strip(), "r").read())
**Note: the above function will read the whole file as a single string (text)
I am trying to edit a specific line of a notepad file using Python 3. I can read from any part of the file and write to the end of it, however whenever I have tried editing a specific line, I am given the error message 'TypeError: 'int' object is not subscriptable'. Does anybody know how I could fix this?
#(This was my first attempt)
f = open('NotepadTester.txt', 'w')
Edit = input('Enter corrected data')
Line = int(input('Which line do you want to edit?'))
f.write(Edit)[Line-1]
f.close()
main()
#(This was my second attempt)
f = open('NotepadTester.txt', 'w')
Line = int(input('Which line do you want to edit?'))
Edit = input('Enter corrected data')
f[Line-1] = (Edit)
main()
you can't directly 'edit' a line in a text file as far as I know. what you could do is read the source file src to a variable data line-by-line, edit the respective line and write the edited variable to another file (or overwrite the input file) dst.
EX:
# load information
with open(src, 'r') as fobj:
data = fobj.readlines() # list with one element for each text file line
# replace line with some new info at index ix
data[ix] = 'some new info\n'
# write updated information
with open(dst, 'w') as fobj:
fobj.writelines(data)
...or nice and short (thanks to Aivar Paalberg for the suggestion), overwriting the input file (using open with r+):
with open(src, 'r+') as fobj:
data = fobj.readlines()
data[ix] = 'some new info\n'
fobj.seek(0) # reset file pointer...
fobj.writelines(data)
You should probably load all the lines into memory first, modify it from there, and then write the whole thing to a file.
f = open('NotepadTester.txt', 'r')
lines = f.readlines()
f.close()
Which_Line = int(input('Which line do you want to edit? '))
Edit = input('Enter corrected data: ')
f = open("NotepadTester.txt",'w')
for i,line in enumerate(lines):
if i == Which_Line:
f.writelines(str(Edit)+"\n")
else:
f.writelines(line)
f.close()
I am trying to pull the data in the csv file below into a dictionary, but my code returns an operation on closed file error.
LotrGrade = {}
with open('grade_list_large.csv', 'r') as FOpen:
line = FOpen.readline()
LotrGrade = {}
for line in FOpen:
grades = []
line = line.rstrip()
Name = line.split(',')
NameKey = Name[0]
GradeValu = list(Name[1])
while True:
if NameKey in LotrGrade.keys()== True:
LotrGrade.setdefault(NameKey).append(GradeValu)
else:
LotrGrade[NameKey] = GradeValu
else:
False
print(LotrGrade)
This is happening because when you use the with keyword to open a file it will automatically close the file at the end of the with block.
So the error is happening at for line in FOpen: because FOpen has been closed.
Two approaches to fix this, either move all the logic into the with statement (this would keep the file open while the script runs), or parse the data out of the file and into a list before the file is closed (open the file to read data then close it). I'd prefer the latter, but it's up to you. Here's an example of the second approach.
data = []
open('grade_list_large.csv', 'r') as FOpen:
for line in FOpen:
data.append(line)
LotrGrade = {}
for d in data:
# do some work
Issue 1
with open('grade_list_large.csv', 'r') as FOpen:
line = FOpen.readline()
LotrGrade = {}
At this point, you close the file FOpen1 after the indented block. If you check the Python docs,
It is good practice to use the with keyword when dealing with file
objects. This has the advantage that the file is properly closed after
its suite finishes, even if an exception is raised on the way
So you can't access FOpen1 in this line
for line in FOpen
to read the lines in the file because you've already closed it.
Issue 2
The following statements don't make any sense
with open('grade_list_large.csv', 'r') as FOpen:
line = FOpen.readline()
LotrGrade = {}
Essentially, you open a file, read one line from it to line and closes it. As of now, you have just read the very first line from the file.
If you modify these statements to
with open('grade_list_large.csv', 'r') as FOpen:
lines = FOpen.readlines()
LotrGrade = {}
You can later on loop through lines as
for line in lines:
# do something
I have date.txt file where are codes
ex:
1111111111111111
2222222222222222
3333333333333333
4444444444444444
I want to check each code in website.
i tried:
with open('date.txt', 'r') as f:
data = f.readlines()
for line in data:
words = line.split()
send_keys(words)
But this copy only last line to.
I need to make a loop that will be checking line by line until check all
thanks for help
4am is to late 4my little brain..
==
edit:
slove
while lines > 0:
lines = lines - 1
with open('date.txt', 'r') as f:
data = f.readlines()
words = data[lines]
print(words)
Try this I think it will work :
line_1 = file.readline()
line_2 = file.readline()
repeat this for how many lines you would like to read.
One thing to keep in mind is if you print these lines they will all print on the same line.