I am currently writing a code that asks a user if they want to either copy the contents of a file and put it into another file and also compare two contents of a file to see if they are identical. The copying part of my file works but not the part with comparing the contents of two files. I get an error saying:
line2=output_file.readlines()
io.UnsupportedOperation: not readable
This is my current code at the moment:
userinput=int(input('Press 1 to copy files, 2 to compare files, anything else to stop')) #prompt user for comparing or copying
while userinput==1 or userinput==2:
if userinput==1:
with open(input('Enter file you want copied:')) as input_file:
with open(input('Enter file you want contents copied to:'), 'w') as output_file:
for line in input_file: #contents of first file copied to second file
output_file.write(line)
userinput=int(input('Press 1 to copy files, 2 to compare files, anything else to stop'))
elif userinput==2:
with open(input('Enter file you want to check')) as input_file:
with open(input('Enter second file you want to check:'), 'w') as output_file:
line1=input_file.readlines() #reads each line of the text
line2=output_file.readlines()
if line1==line2: #checks if text is identical to each other
print('files are identical')
userinput=int(input('Press 1 to copy files, 2 to compare files, anything else to stop'))
elif line1 != line2:
print('This is where the file deviates')
print(line1)
print(line2)
userinput=int(input('Press 1 to copy files, 2 to compare files, anything else to stop'))
What can I do to fix this?
You are trying to read the file but u open the file as write-able with the argument 'w'
with open(input('Enter second file you want to check:'), 'w') as
output_file:
Either remove the argument or replace 'w' with 'r'
with open(input('Enter second file you want to check:')) as
output_file:
OR
with open(input('Enter second file you want to check:'), 'w') as
output_file:
You opened the output file output_file for writing ('w'). You cannot read from it. Change 'w' to 'r'.
Related
some_file.txt: (berore)
one
two
three
four
five
...
How can I effectively modify large file in Python?
with open("some_file.txt", "r+") as file:
for idx, line in enumerate(file.readlines()):
file.writeline(f'{idx} {line}') # something like this
some_file.txt: (after)
1 one
2 two
3 three
4 four
5 five
...
Don't try to load your entire file in memory, because the file may be too large for that. Instead, read line by line:
with open('input.txt') as inp, open('output.txt', 'w') as out:
idx = 1
for line in inp:
out.write(f'{idx} {line}'
idx += 1
You can't insert into the middle of a file without re-writing it. This is an operating system thing, not a Python thing.
Use pathlib for path manipulation. Rename the original file. Then copy it to a new file, adding the line numbers as you go. Keep the old file until you verify the new file is correct.
Open files are iterable, so you can use enumerate() on them directly without having to use readlines() first. The second argument to enumerate() is the number to start the count with. So the loop below will number the lines starting with 1.
from pathlib import Path
target = Path("some_file.txt")
# rename the file with ".old" suffix
original = target.rename(target.with_suffix(".old"))
with original.open("r") as source, target.open("w") as sink:
for line_no, line in enumerate(source, 1):
sink.writeline(f'{line_no} {line}')
Hello I am very new to coding, I am writing small python script but I am stuck. The goal is to compare the log.txt contents to the contents of the LargeFile.txt and every line of the log.txt that is not matching to any line of the LargeFile.txt to be stored in the outfile.txt but with the code below I only get the First line of the log.txt to repeat itself in the outfile.txt
logfile = open('log1.txt', 'r') # This file is 8KB
keywordlist = open('LargeFile.txt', 'r') # This file is 1,4GB
outfile = open('outfile.txt', 'w')
loglines = [n for n in logfile]
keywords = [n for n in keywordlist]
for line in loglines:
for word in keywords:
if line not in word:
outfile.write(line)
outfile.close()
So conceptually you're trying to check whether any line of your 1+ GB file occurs in your 8 KB file.
This means one of the files needs to be loaded into RAM, and the smaller file is the natural choice. The other file can be read sequentially and does not need to be loaded in full.
We need
a list of lines from the smaller file
an index of those lines for quick look-ups (we'll use a dict for this)
a loop that runs through the large file and checks each line against the index, making note of every matching line it finds
a loop that outputs the original lines and uses the index to determine whether they are unique or not.
The sample below prints the complete output to the console. Write it to a file as needed.
with open('log1.txt', 'r') as f:
log_lines = list(f)
index = {line: [] for line in log_lines}
with open('LargeFile.txt', 'r') as f:
for line_num, line in enumerate(f, 1):
if line in index:
index[line].append(line_num)
for line in log_lines:
if len(index[line]) == 0:
print(f'{line} -> unique')
else:
print(f'{line} -> found {len(index[line])}x')
I want to know how I can search for a specific word in a .txt file using Python3.
If the word 'pizza' is included in the .txt file, then it should (e.g.) import another python program.
You can iterate through each line in the file with a 'for' loop and check to see if the string is in the line:
f = open('file.txt', 'r')
for line in f:
if 'pizza' in line:
# do whatever you want here
print("Found it!")
else:
pass
with open('file.txt', 'r') as searchfile:
for line in searchfile:
if 'searchphrase' in line:
print line
Hi guy's,
So I have 1200 files to search through, in these 1200 files I need to -
Copy the first line of every file into one new text document, followed by below.
After pulling the first line of the document I need to search the rest of the file for my "Search phrase" - then copy that search phrase line along with the 10 following lines. Close file and move on to the next.
All the files are locate inside one master file, with uniform names.
Eg:
file 1
file 2
file 3
file 4
file 5 and so on...
I'v been trying for days but cannot seem to get it. This could save me 14 days of work.
Any help at all would be really appreciated.
Found a solution!
with open("C:\file.txt") as infile, open("C:\outfile.txt", "w") as outfile:
copy = False
for line in infile:
if line.strip() == "Start-Phrase":
copy = True
elif line.strip() == "End-Phrase":
copy = False
elif copy:
outfile.write(line)
I have 2 files
export_f= open (../../sim_export/modelsim/compile.do)
comp_file = open (../../ver/sim/xilinx_compile.tcl)
I have to append the content of export_f after the 4 first lines of comp_file (all the lines after should be deleted)
export_f= open ('compile.do', 'r')
comp_file = open ('xilinx_compile.tcl', 'r+')
with open('comp_file.temp', 'w') as temp:
temp.writelines(comp_file.readlines()[0:4])
temp.writelines(export_f)
This will create a new file named comp_file.temp that contains the first 4 lines of comp_file followed by all the contents of export_f.
It's also possible to replace the original comp_file with the new contents, or simply rename the new comp_file.temp to replace the original comp_file.
Hope this helps.