This question already has answers here:
How to read a text file into a string variable and strip newlines?
(27 answers)
Closed 4 years ago.
In a program, you can simulate a magic square by using a two-dimensional list. Write a Python program that tests whether or not a 3 by 3 grid is a valid magic square. The program reads the input from a text file named input.txt. Each line in the file contains exactly 9 numbers that correspond to the the second row, and the last three values correspond to the last row.
I am not struggling with how to create the program to check to see if the square is a magic square, but how do I read in the "input.txt" into the program when I run it?
If you're looking only for how to read the input.txt file, you can just do this:
f = open('input.txt', 'r'):
f.read()
Provided your input.txt file is in current path.
Related
This question already has answers here:
read the whole file at once
(2 answers)
Closed 7 months ago.
Let us say I wanted to read a whole file at once instead of going through it line by line (let's say for example to speed up retrieval of the times 'i' occurs in the file). How would I go about reading it as a whole instead of the lines in which it is written?
with open("file.ext", 'r') as f:
data = f.read()
As others have mentioned, you can find an official Python tutorial for Reading and Writing Files which explains this. You can also see the Methods of File Objects section, which explains the use of f.read(size) and f.readline() and the difference between between them.
This question already has answers here:
Print string to text file
(8 answers)
Closed 1 year ago.
I'm looking for a way to get the output that I'm printing out here written in a .txt file
for y in list(permutations(sllist, 3)):
print("".join(y))
The Output in the console looks like that:
ccccaaaaaaaabbbbdddddddddd
ccccaaaaaaaabbbbeeeeeee
ccccaaaaaaaabbbbfff
ccccaaaaaaaabbbbgggggggggggg
ccccaaaaaaaabbbb2001
ccccaaaaaaaabbbb01
ccccaaaaaaaabbbb06
And that's exactly how I want to write it in the .txt file. Neatly arranged among each other.
Thanks in advance.
Use a context manager to open the file, so that it will be automatically and correctly closed, even if the code inside raises exceptions.
As pointed out in the comments, there is no need to create the whole list in memory, you can iterate over the object returned by permutations and each element will be produced as needed.
from itertools import permutations
sllist = "abcd"
with open("output.txt", "w") as f:
for y in permutations(sllist, 3):
line = "".join(y)
print(line)
f.write(f"{line}\n")
Cheers!
This question already has answers here:
How to search and replace text in a file?
(22 answers)
Closed 5 years ago.
I am trying to search through a jsp file, see if it contains a certain tag, and replace an attribute on the same line if the tag exists on the same line.
For example <c:out var="taskToRedirect" property="dueDate"
I am trying to see if the line contains <c:out and if it does, I need to change the "property" attribute to "value", and only on that line, I don't want to change all of the "property" attributes in the entire file.
Currently what I have is:
f = open(filepath)
c = f.read()
for i in c:
if ("<c:out" in i):
c=c.replace(i,i.replace("property","value"))
f.write(c)
f.close()
The code appears to do nothing, and throws no run time errors, c is the string representation of the contents of a file, and i is the current line in the file. Any suggestions are welcome.
I don't see where you write the output. The file doesn't change unless you write out those changes. c is only your internal copy.
Have you traced whether c changes as expected? Have you tried this with a small file?
This question already has answers here:
Read file from line 2 or skip header row
(8 answers)
Closed 8 years ago.
Structure of fasta file is like this:
>gi|568815364|ref|NT_077402.3| Homo sapiens chromosome 1 genomic scaffold, GRCh38 Primary Assembly HSCHR1_CTG1
TAACCCTAACCCTAACCCTAACCCTAACCCTAACCCTAACCCTAACCCTAACCCTAACCCTAACCCTAAC
CCTAACCCTAACCCTAACCCTAACCCTAACCCTAACCCAACCCTAACCCTAACCCTAACCCTAACCCTAA
CCCTAACCCCTAACCCTAACCCTAACCCTAACCCTAACCTAACCCTAACCCTAACCCTAACCCTAACCCT
AACCCTAACCCTAACCCTAACCCCTAACCCTAACCCTAAACCCTAAACCCTAACCCTAACCCTAACCCTA
ACCCTAACCCCAACCCCAACCCCAACCCCAACCCCAACCCCAACCCTAACCCCTAACCCTAACCCTAACC
The first line is some information about the content of file and rest lines are strand of DNA, RNA or amino acid.
To do some work with this kind of file I need to remove first line of file. How can I do this using python?
I tried this code, but its not suitable:
My_string=open("SimpleFastaFile.fa", "r").read()
def line_remove(str):
if str.isalnum()==False:
str=str[1:]
line_remove(str)
line_remove(My_string)
you can use next to advanced pointer to nextline:
my_string = open("SimpleFsastaFile.fa", "r")
next(my_string) # advanced file pointer to next line
my_string.read()
If you need the whole file's content, why not read all lines at once and immediately slice away the first line?
with open('path','r') as f:
content = f.readlines()[1:]
output="".join(content)
This question already has an answer here:
Python: Creating a list from a file
(1 answer)
Closed 8 years ago.
I am creating a sort and I need a list of integers which will be taken from a text file. How can I feed data from a text file into a list of of integers. it is just one int on every line of the text file. My guess was just make an empty list and say list.append(int(f.readline)) but I am not sure. There is no actual code because I wanted understand this logic first.
You can get all lines with file.readlines() and then iterate over them easily.
Try this:
filename = "PATH TO YOUR FILE"
result = []
with open(filename, 'r') as fp:
for line in fp.readlines():
result.append(int(line))
# If you want your list sorted, uncomment the following line
#result.sort()