What I Want
I have written a code that opens a file (currentcode) gets it's text finds it in another file (text.txt) and replaces currentcode with a new int.
My Code
import os
currentcode = open('currentcode.txt','r+')
code = currentcode.read()
print('Choose File: ')
print('1: File One > ')
file = input('Enter Number Of File: ')
file = 'C:/text.txt'
old_text = code
new_text = str(int(code) + 1)
print('Opened File')
f1 = open(file, 'r')
f2 = open(file, 'w')
f2.write(replace(old_text, new_text))
currentcode.write(new_text)
f1.close()
f2.close()
Output After Running
When I Run This Code I Get:
Choose File:
1: File One >
Enter Number Of File: 1
Opened File
Traceback (most recent call last):
File "C:\Users\DanielandZoe\Desktop\scripys\Replace.py", line 18, in <module>
f2.write(replace(old_text, new_text))
NameError: name 'replace' is not defined
NameError: name 'replace' is not defined
That means python couldn't find a module, class or function called 'replace'.
If you want to replace text on a file, you need to get its contents as a string, not as a file-like object (like you're doing now), then you replace the contents using the replace method on your string and finally, write the contents to the desired file.
string.replace() is a method for strings:
https://docs.python.org/2/library/string.html#string.replace
what is in f2? Not a string. You should read the lines of the file.
Related
I tried running this code in python. I ensured:
The .txt file was in the same file as the code file and the file name was "random.txt" saved in .txt format
file = input ('Enter File:')
if len(file) < 1 : file = 'random.txt'
fhan = open(file)
print (fhan)
My command prompt returned me <_io.TextIOWrapper name='random.txt' mode='r' encoding='cp1252'> with no traceback. I don't know how to get the file to open and print the content
Open a file, and print the file content:
with open('./demo.txt', 'r') as file:
txt = file.read()
print(txt)
fhan is a file handle, so printing it simply prints the results of calling its repr method, which shows what you see. To read the entire file, you can call fhan.read().
It's also good practice to use a with statement to manage resources. For example, your code can be written as
file = input('Enter File:')
if not file: # check for empty string
file = 'random.txt'
with open(file, 'r') as fhan: # use the `with` statement
print(fhan.read())
The benefit of this syntax is that you'll never have to worry about forgetting to close the file handle.
I am writing a simple program that reads a file, copies its contents and writes the copied content into a new file. I thought I had done it correctly, because when I open "copyFile" the copied contents of the original file is written there as a string. I've written:
copy = open('TestFile').read() #Open 'TestFile', read it into variable
print("Copy of textfile:\t", copy)
copyFile = open('copyText.txt', 'w').write(copy) #Create new file, write in the copied text
copyText = copyFile.read()
print("New file :\t", copyText)
And I am able to print the contents of the file, but when I try to print the copy, i get this error:
Traceback (most recent call last):
File "PATH/TO/THE/FILE/CALLED/copyText.py", line 14, in <module>
copyText = copyFile.read()
AttributeError: 'int' object has no attribute 'read'
The file only has one sentence in it, so I don't understand the error i'm getting.
File write do not return io object. It returns length of the text written.
Also i suggest you should use with statement to write and read from file.
The following code is the right way to do it for your case.
copy = open('TestFile').read() #Open 'TestFile', read it into variable
print("Copy of textfile:\t", copy)
length = open('copyText.txt', 'w').write(copy) #Create new file, write in the copied text
copyText = open('copyText.txt', 'r').read()
print("New file :\t", copyText)
This is the solution you should use to read and write.
with open('TestFile', 'r') as readfile:
copy = readfile.read()
print("Copy of textfile:\t", copy)
with open("copyTest.txt", 'w') as writefile:
length = writefile.write(copy)
print("Length written to file", length)
with open("copyTest.txt", 'r') as readfile:
copyText = readfile.read()
print("New file:\t", copyText)
output
Copy of textfile: this is a sentence
Length written to file 19
New file: this is a sentence
TestFile:
this is a sentence
It looks like the write function is outputting the number of characters that were written to the file, which means you are trying to call read on an int.
You'll want to store the file in a variable before trying to write to it, if you want to read in the file text afterwards. This can be achieved like the following
copy = open('TestFile').read() #Open 'TestFile', read it into variable
print("Copy of textfile:\t", copy)
copyFile = open('copyText.txt', 'w') #Create new file
copyFile.write(copy) # write in the copied text
copyText = copyFile.read()
print("New file :\t", copyText)
I have a file that I open and i want to search through till I find a specific text phrase at the beginning of a line. I then want to overwrite that line with 'sentence'
sentence = "new text" "
with open(main_path,'rw') as file: # Use file to refer to the file object
for line in file.readlines():
if line.startswith('text to replace'):
file.write(sentence)
I'm getting:
Traceback (most recent call last):
File "setup_main.py", line 37, in <module>
with open(main_path,'rw') as file: # Use file to refer to the file object
ValueError: must have exactly one of create/read/write/append mode
How can I get this working?
You can open a file for simultaneous reading and writing but it won't work the way you expect:
with open('file.txt', 'w') as f:
f.write('abcd')
with open('file.txt', 'r+') as f: # The mode is r+ instead of r
print(f.read()) # prints "abcd"
f.seek(0) # Go back to the beginning of the file
f.write('xyz')
f.seek(0)
print(f.read()) # prints "xyzd", not "xyzabcd"!
You can overwrite bytes or extend a file but you cannot insert or delete bytes without rewriting everything past your current position.
Since lines aren't all the same length, it's easiest to do it in two seperate steps:
lines = []
# Parse the file into lines
with open('file.txt', 'r') as f:
for line in f:
if line.startswith('text to replace'):
line = 'new text\n'
lines.append(line)
# Write them back to the file
with open('file.txt', 'w') as f:
f.writelines(lines)
# Or: f.write(''.join(lines))
You can't read and write to the same file. You'd have to read from main_path, and write to another one, e.g.
sentence = "new text"
with open(main_path,'rt') as file: # Use file to refer to the file object
with open('out.txt','wt') as outfile:
for line in file.readlines():
if line.startswith('text to replace'):
outfile.write(sentence)
else:
outfile.write(line)
Not the problem with the example code, but wanted to share as this is where I wound up when searching for the error.
I was getting this error due to the chosen file name (con.txt for example) when appending to a file on Windows. Changing the extension to other possibilities resulted in the same error, but changing the file name solved the problem. Turns out the file name choice caused a redirect to the console, which resulted in the error (must have exactly one of read or write mode): Why does naming a file 'con.txt' in windows make Python write to console, not file?
I'm a beginner. I have written a Python program with the following pseduocode:
Define Function1.
a. This function takes a large single-fasta file (a genome) and splits it into pieces.
b. These pieces are written to a multi-fasta output file (ex. below).
Define Function2.
a. This function reads the lines of the multi-fasta file
b. Writes to an output file the fasta id followed by the length of the fasta entry.
most of the code:
from Bio import SeqIO
import io
def metagenome_simulator(genome_fasta, out_file):
outfile = open(out_file, "a+b")
fasta = SeqIO.parse(open(genome_fasta, "rU"), "fasta")
#does the split, blah, blah - I know this function works on its own already
len_file.close()
fasta.close()
return outfile
def contig_len_calculator(fasta, out_file):
outfile = io.open(out_file, "wb")
fhandle = io.open(fasta, "a+b")
outfile.write("contig_id" + "\t" + "contig_length" + "\n")
for entry in SeqIO.parse(fhandle, "fasta"):
#calculates lengths, blah, blah - i know this works independently too
outfile.close()
fhandle.close()
return
def main():
output = metagenome_simulator(sys.argv[1], sys.argv[2])
print(output)
contig_len_calculator(output, sys.argv[3])
main()
And my command (bash shell) would be:
./this_script.py genome_fasta_file split_fasta_out_file final_output_file.
The output would be two separate files, one for each function in the program. The first would be the split fasta:
>split_1
ATCG....
>split_2
ATCG....
.
.
.
And the second would be the lengths file:
>split_1 300
>split_2 550
.
.
.
This does not work. It runs Fuction1 just fine and makes the split_fasta_output file but then returns:
<open file 'out_file', mode 'a+b' at 0x7f54b8454d20>
Traceback (most recent call last):
File "./this_script.py", line 62, in <module>
main()
File "./this_script.py", line 60, in main
contig_len_calculator(output, sys.argv[3])
File "./this_script.py", line 47, in contig_len_calculator
fhandle = io.open(fasta, "a+b")
TypeError: invalid file: <open file 'out_file', mode 'a+b' at 0x7f54b8454d20>
I have no idea why it doesn't work. So my question is this: how do I properly pass a file created in one function to another function?
EDIT: Put the whole traceback error.
The problem is that metagenome_simulator returns a file descriptor, which you then try to pass into io.open. io.open takes either an integer file descriptor (some_fd.fileno()) or a path. The simple solution is then to return the path to your outfile, rather than the outfile itself.
def metagenome_simulator(genome_fasta, out_file):
... # your code as-written
return out_file
But if you like you could instead do:
def metagenome_simulator(genome_fasta, out_file):
# completely as-written, including
return outfile
def contig_len_calculator(fasta, out_file):
outfile = io.open(out_file, "wb")
fhandle = io.open(fasta.fileno(), "a+b")
...
The advantage of the first approach is that it makes the out_file and fasta arguments to contig_len_calculator have the same type, which seems sane.
The open function takes a filename and returns a file object. metagenome_simulator returns a file object. You pass this as fasta and then use open on it. But you do not need to open it since it's already an open file and not just a filename.
I am trying to read a fastq file four lines at a time. There are several lines in the file. but when I put in my code, I get this:
Traceback (most recent call last):
File "fastq.py", line 11, in
line1 = fastq_file.readline()
AttributeError: 'str' object has no attribute 'readline'
This is my code:
import Tkinter, tkFileDialog #asks user to select a file
root = Tkinter.Tk()
root.withdraw()
fastq_file = tkFileDialog.askopenfilename()
if fastq_file.endswith('.fastq'): #check the file extension
minq = raw_input("What is your minimum Q value? It must be a numerical value.") #receives the minimum Q value
while True:
line1 = fastq_file.readline()
if not line1:break
line2 = fastq_file.readline(2)
line3 = fastq_file.readline(3)
line4 = fastq_file.readline(4)
txt = open(practice.text)
txt.write(line1) #puts the lines into the file
txt.write("\n")
txt.write(line2)
txt.write("\n")
txt.write(line3)
txt.write("\n")
txt.write(line4)
txt.write("\n")
print "Your task is complete!"
else:
print "The file format is not compatible with the FastQ reader program. Please check the file and try again."
How would I fix it so that I can assign each line to a string and then write those strings in a text file?
You need to open the file first
while True:
with open(fastq_file) as fastq_file_open:
line1 = fastq_file_open.readline()
You probably want to open them before you actually get to the while loop, but I don't have the rest of your code, so I can't structure it that exactly.
You have to open the file like this.
fastq_file = open("fastq_file","r")
Then execute your code.
And also.
txt = open("practice.text","w") # you have to pass a string and open it in write mode.
By the way, you don't need to use readline(<number>), it only reads <number> characters from the current cursor position. After executing one readline(), the cursor moves to after next newline character and for next readline(), it starts to read from there. So just use readline().
Anyway I don't know what you are trying to achieve. But the code looks like you are trying to copying the context from fastq_file to practice.text, which can be done just by copying the file (using shutil.copyfile).
what is fastq_file? your code is incorrect. if, fastq_file were a file descriptor, it cannot be an str object.