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.
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.
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.
hey I've wrote this code in python and it iterates through the selected text file and reads it. My objective is to read the file, and then write the file on a new file and replace the word "winter" with nothing. or rather delete the word from the second revised file. I have two txt files called odetoseasons and odetoseasons_censored the contents of these two files are identical before the program starts. which is
I love winter
I love spring
Summer, Fall and winter again.
/This is the python file named readwrite.py WHen i run the program it keeps the contents in odetoseasons but somehow deletes the contents of odetoseasons_censored.txt not sure why/
# readwrite.py
# Demonstrates reading from a text file and writing to the other
filename = input("Enter file name (without extension): ")
fil1 = filename+".txt"
fil2 = filename+"_censored.txt"
bad_word = ['winter']
print("\nLooping through the file, line by line.")
in_text_file = open(fil1, "r")
out_text_file = open(fil2,"w")
for line in in_text_file:
print(line)
out_text_file.write(line)
in_text_file.close()
out_text_file.close()
out_text_file = open(fil2,"w")
for line in fil2 :
if "winter" in line:
out_text_file.write(line)
line.replace("winter", "")
Actually there are two errors in your code. Firstly the function a.replace() returns an object with the replaced word and not alter the original object. Secondly you are trying to read a file you have opened in 'w' mode, which is not possible. If you need to both read and write you should use 'r+' mode.
Here is the correct code(and more compact one) that you can use :-
filename = input("Enter file name (without extension): ")
fil1 = filename+".txt"
fil2 = filename+"_censored.txt"
bad_word = ['winter']
print("\nLooping through the file, line by line.")
in_text_file = open(fil1, "r")
out_text_file = open(fil2,"w")
for line in in_text_file:
print(line)
line_censored = line.replace("winter","")
print(line_censored)
out_text_file.write(line_censored)
in_text_file.close()
out_text_file.close()
I'm trying to write a Python script that will take any playlist and recreate it on another file structure. I have it written now so that all the filenames are stripped off the original playlist and put into a file. That works. Then the function findsong() is supposed to walk thru the new directory and find the same songs and make a new playlist based on the new directory structure.
Here's where it gets weird. If I use 'line' as my argument in the line 'If line in files' I get an empty new playlist. If I use ANY file that I know is there as the argument the entire playlist is recreated, not just the file I used as the argument. That's how I have it set up in this code. I cannot figure out this weird behavior. As long as the file exists, the whole playlist is recreated with the new paths. Wut??
Here is the code:
import os
def check():
datafile = open('testlist.m3u')
nopath = open('nopath.txt', 'w')
nopath.truncate()
for line in datafile:
if 'mp3' in line:
nopath.write(os.path.basename(line))
if 'wma' in line:
nopath.write(os.path.basename(line))
nopath.close()
def findsong():
nopath = open('nopath.txt')
squeezelist = open('squeezelist.m3u' ,'w')
squeezelist.truncate()
for line in nopath:
print line
for root, dirs, files in os.walk("c:\\Documents and Settings\\"):
print files
if ' Tuesday\'s Gone.mp3' in files:
squeezelist.write(os.path.join(root, line))
squeezelist.close()
check()
findsong()
When you iterate over the lines in a file Python retains the trailing newlines \n. You'll want to strip those off:
for line in nopath:
line = line.rstrip()
I'm a beginner in programming and have decided to teach myself Python. After a few days, i've decided to code a little piece. I's pretty simple:
date of today
page i am at (i'm reading a book)
how i feel
then i add the data in a file. every time i launch the program, it adds a new line of data in the file
then i extract the data to make a list of lists.
truth is, i wanted to re-write my program in order to pickle a list and then unpickle the file. However, as i'm coping with an error i can't handle, i really really want to understand how to solve this. Therefore i hope you will be able to help me out :)
I've been struggling for the past hours on this apparently a simple and stupid problem. Though i don't find the solution. Here is the error and the code:
ERROR:
Traceback (most recent call last):
File "dailyshot.py", line 25, in <module>
SaveData(todaysline)
File "dailyshot.py", line 11, in SaveData
mon_pickler.dump(datatosave)
TypeError: must be str, not bytes
CODE:
import pickle
import datetime
def SaveData(datatosave):
with open('journey.txt', 'wb') as thefile:
my_pickler = pickle.Pickler(thefile)
my_pickler.dump(datatosave)
thefile.close()
todaylist = []
today = datetime.date.today()
todaylist.append(today)
page = input('Page Number?\n')
feel = input('How do you feel?\n')
todaysline = today.strftime('%d, %b %Y') + "; " + page + "; " + feel + "\n"
print('Thanks and Good Bye!')
SaveData(todaysline)
print('let\'s make a list now...')
thefile = open('journey.txt','rb')
thelist = [line.split(';') for line in thefile.readlines()]
thefile.close()
print(thelist)
Thanks a looot!
Ok so there are a few things to comment on here:
When you use a with statement, you don't have to explicitly close the file. Python will do that for you at the end of the with block (line 8).
You don't use todayList for anything. You create it, add an element and then just discard it. So it's probably useless :)
Why are you pickling string object? If you have strings just write them to the file as is.
If you pickle data on write you have to unpickle it on read. You shouldn't write pickled data and then just read the file as a plain text file.
Use a for append when you are just adding items to the file, w will overwrite your whole file.
What I would suggest is just writing a plain text file, where every line is one entry.
import datetime
def save(data):
with open('journey.txt', 'a') as f:
f.write(data + '\n')
today = datetime.date.today()
page = input('Page Number: ')
feel = input('How do you feel: ')
todaysline = ';'.join([today.strftime('%d, %b %Y'), page, feel])
print('Thanks and Good Bye!')
save(todaysline)
print('let\'s make a list now...')
with open('journey.txt','r') as f:
for line in f:
print(line.strip().split(';'))
Are you sure you posted the right code? That error can occur if you miss out the "b" when you open the file
eg.
with open('journey.txt', 'w') as thefile:
>>> with open('journey.txt', 'w') as thefile:
... pickler = pickle.Pickler(thefile)
... pickler.dump("some string")
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
TypeError: must be str, not bytes
The file should be opened in binary mode
>>> with open('journey.txt', 'wb') as thefile:
... pickler = pickle.Pickler(thefile)
... pickler.dump("some string")
...
>>>