String search and write into a file in jython - string

I wish to write a program that can read a file and if a particular str_to_find is found in a bigger string, say
"AACATGCCACCTGAATTGGATGGAATTCATGCGGGACACGCGGATTACACCTATGAGCAGAAATACGGCCTGCGCGATTACCGTGGCGGTGGACGTTCTTCCGCGCGTGAAACCGCGATGCGCGTAGCGGCAGGGGCGATCGCCAAGAAATACCTGGCGGAAAAGTTCGGCATCGAAATCCGCGGCTGCCTGACCCAGATGGGCGACATTCCGCTGGAGATTAAAGACTGGCGTCAGGTTGAGCTTAATCCGTTTTC"
then write that line and the above line of it into the file and keep repeating it for all the match found.
Please suggest the solution. I have written the program for printing that particular search line but I don't know how to write the above line.
import re
import string
file=open('C:/Users/Administrator/Desktop/input.txt','r')
output=open('C:/Users/Administrator/Desktop/output.txt','w')
count_record=file.readline()
str_to_find='AACCATGC'
while count_record:
if string.find(list,str_to_find) ==0:
output.write(count_record)
file.close()
output.close()

one way
for line in open("file"):
if "str_to_find" in line:
print prev
print line.rstrip()
prev=line.rstrip()

Related

file reading in python usnig different methods

# open file in read mode
f=open(text_file,'r')
# iterate over the file object
for line in f.read():
print(line)
# close the file
f.close()
the content of file is "Congratulations you have successfully opened the file"! when i try to run this code the output comes in following form:
c (newline) o (newline) n (newline) g.................
...... that is each character is printed individually on a new line because i used read()! but with readline it gives the answer in a single line! why is it so?
r.read() returns one string will all characters (the full file content).
Iterating a string iterates it character wise.
Use
for line in f: # no read()
instead to iterate line wise.
f.read() returns the whole file in a string. for i in iterates something. For a string, it iterates over its characters.
For readline(), it should not print the line. It would read the first line of the file, then print it character by character, like read. Is it possible that you used readlines(), which returns the lines as a list.
One more thing: there is with which takes a "closable" object and auto-closes it at the end of scope. And you can iterate over a file object. So, your code can be improved like this:
with open(text_file, 'r') as f:
for i in f:
print(i)

Python:Reading specific line from user and show the line

problem: Write your own version of code that prompts for the name of the file to read, and the number of lines to print.
Can anyone help me to solve this problem in python?
I tried to like this :
import linecache
line=int(input("Line: "))
print(linecache.getline("Test.txt",line))
but can't solve the last problem where it said if the input is greater then the lines that already exist, all lines will be shown
file=input('File name: ')
print(os.access(file,os.F_OK))#check whether file is available or not
no_of_lines=int(input('Lines: '))
file_length=0
with open(file,'r') as f:
file_length=len(f.readlines())
with open(file,'r') as f:
if file_length<no_of_lines:
print(f.read())
else:
for i in range(no_of_lines):
print(f.readline().rstrip('\n'))

Python3, read specific word from .txt file

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

Using for loop to strip white space and resetting the pointer prior to reading a file

I'm using Pycharm and have been very happy so far. However, today I ran into a issue that I can't figure out or explain. The code will prompt the user for an input file. The file is a .txt file that contains lines of words. After the user provides the filename, the program will open it, remove white spaces at the end of the lines and print the contents of the file. (lots_of_words.txt = example)
INPUT
print(lots_of_words.txt)
OUTPUT
Programming is fun and will save the world from errors! ....
Here is the part of the code that is causing the confusion:
user_input = input('Enter the file name: ')
open_file = open(user_input)
for line in open_file:
line = line.rstrip()
read_file = open_file.read()
print(read_file)
OUTPUT
Process finished with exit code 0
Now by just removing the for loop with string.rstrip(), the text file prints fine:
INPUT
user_input = input('Enter the file name: ')
open_file = open(user_input)
# Removed for loop
read_file = open_file.read()
print(read_file)
OUTPUT
Programming is fun and will save the world from errors! ....
I'm using python 3.4 with Pycharm IDE. I realize that the script completed fine without errors, but why won't it print the final variable? I'm sure this is a simple answer, but I can't figure it out.
Running the same code in Python 2.7, prints fine even with string.rstrip().
It has nothing to do with PyCharm.
Your for moves the pointer to the end of the file. To use open_file again, use seek(0), before printing.
open_file = open(user_input)
for line in open_file:
line = line.rstrip()
open_file.seek(0)
read_file = open_file.read()
print(read_file)
Not the most efficient solution though (if efficiency matters in given situation), since you read all the lines twice. You can either store each line after reading it (as suggested in the other answer), or print each line after striping it.
Also, rstrip() will remove whitespaces at the end of the string, but not '\n'.
Irrelevant: You should use with open() as.. : instead of open() since it closes the file automatically.
Iterating over your file object in the for loop will consume it, so there will be nothing left to read, you're simply discarding all lines.
If you want to strip all whitespace from all lines, you could use:
user_input = input('Enter the file name: ')
open_file = open(user_input)
lines = []
for line in open_file:
lines.append(line.rstrip())
print(''.join(lines))
or even shorter:
print(''.join(line.rstrip() for line in open_file))

User input after file input in Python?

First year Comp Sci student here.
I have an assignment that is asking us to make a simple game using Python, which takes an input file to create the game-world (2D grid). You're then supposed to give movement commands via user input afterwards. My program reads the input file one line at a time to create the world using:
def getFile():
try:
line = input()
except EOFError:
line = EOF
return line
...after which it creates a list to represent the line, with each member being a character in the line, and then creates a list containing each of these lists (amounting to a grid with row and column coordinates).
The thing is, I later need to take input in order to move the character, and I can't do this because it still wants to read the file input, and the last line from the file is an EOF character, causing an error. Specifically the "EOF when reading a line" error.
How can I get around this?
Sounds like you are reading the file directly from stdin -- something like:
python3 my_game.py < game_world.txt
Instead, you need to pass the file name as an argument to your program, that way stdin will still be connected to the console:
python3 my_game.py game_world.txt
and then get_file looks more like:
def getFile(file_name):
with open(file_name) as fh:
for line in fh:
return line
File interaction is python3 goes like this:
# the open keyword opens a file in read-only mode by default
f = open("path/to/file.txt")
# read all the lines in the file and return them in a list
lines = f.readlines()
#or iterate them at the same time
for line in f:
#now get each character from each line
for char_in_line in line:
#do something
#close file
f.close()
line terminator for the file is by default \n
If you want something else you pass it as a parameter to the open method (the newline parameter. Default=None='\n'):
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Resources