IDLE isn't opening and reading a text file - python

I'm trying to open a text file that will allow me to read multiple lines and have them become capitalised
inputFileName = input("Input file name: ")
infile = open(inputFileName, "w+")
infile = open(inputFileName, "a")
infile = open(inputFileName, "r+")
line = infile.readline()
while line != "" :
line = infile.readline()
line = line.upper()
outfile.write(line)
print(line)
infile.close()
When opening it would not give the context of the file itself, even though what I wrote should work

as the comments have begun to mention, and in reference to your final statement, this code absolutely should not work, for multiple reasons.
1) you open the file three times, for no apparent reason.
2) outfile isn't declared, doesn't do anything.
3) when you open a file with w it clears the contents of afformentioned file.
firstly fix these issues.
you understand the fundementals, your upper function is fine etc etc.
this is what you must do.
1) dont open the same file 3 times for no reason
2) define outfile
3) use a instead of w so you append rather then delete and write

This will work.
f_name = input("Input file name: ")
with open(f_name, "r+") as f:
lines = f.read().splitlines() # get string, split lines
lines = [l.capitalize() for l in lines] # capitalize each line
f.seek(0) # move the cursor to the beginning
f.write('\n'.join(lines)) # join the lines and write to the same file

Related

Python removing line from text file is removing everything

I'm trying to remove one line which matches a variable. But instead it is wiping the file clean.
a_file = open("./Variables/TxtFile.txt", "r")
lines = a_file.readlines()
a_file.close()
new_file = open("./Variables/TxtFile.txt", "w")
for line in lines:
if line.strip("\n") == VariableStore:
new_file.write(line)
new_file.close()
The goal would be to remove the line that matches VariableStore rather than wiping the entire text file
In regard to my comment to your original post.
You only write to the file if you match the line you want to remove and then also close the file.
This seems not to be what you want.
You might want to change the if condition to be executed in cases that do not match your line you want to remove, i.e., to if not line.strip("\n") == VariableStore: and close the file after your loop, i.e., on the same level as your for loop.
Try the following, which incorporates these suggestions:
a_file = open("./Variables/TxtFile.txt", "r")
lines = a_file.readlines()
a_file.close()
new_file = open("./Variables/TxtFile.txt", "w")
for line in lines:
if not line.strip("\n") == VariableStore:
new_file.write(line)
new_file.close()
If your aim is to filter out the line matching VariableStore, do this:
with open("./Variables/TxtFile.txt", "r") as a_file:
lines = a_file.readlines()
with open("./Variables/TxtFile.txt", "w") as new_file:
for line in lines:
if line.strip("\n") != VariableStore:
continue # Skip the VariableStore line
new_file.write(line) # Write other lines
When you use with statements, you don't need to manually close the file.
You just need to close the file later on, when you are done parsing all the lines.
Also, you need to write the lines that don't match, not the one's that do.
Note the changes below:
# Read file
a_file = open("./Variables/TxtFile.txt", "r")
lines = a_file.readlines()
a_file.close()
# Write file
new_file = open("./Variables/TxtFile.txt", "w")
for line in lines:
if line.strip("\n") == VariableStore:
# Don't write this line
pass
else:
new_file.write(line)
new_file.close()
Let us assume that your text file TxtFile.txt contains this text
Hello
World
I'm
Python
Developer
And you have a variable var contains the string World which we want to remove from the text file.
Here is a python code does the job in few lines
var='World' # a string to remove
with open("TxtFile.txt","r+") as f:
lines = f.readlines()
lines = [line for line in lines if line.strip()!=var]
f.seek(0)
f.writelines(lines)
f.truncate()
The text file after running this code..
Hello
I'm
Python
Developer
The problem is that you're opening the file with write mode instead of append mode. Replace
new_file = open("./Variables/TxtFile.txt", "w")
with
new_file = open("./Variables/TxtFile.txt", "a")
and you'll append the data instead of overwriting it.
Also, it's generally recommended to open files using the 'with' statement, since that automatically closes the file for you.
with open("./Variables/TxtFile.txt", "a") as text_file:
...

Overwriting lines in text file [duplicate]

How can I insert a string at the beginning of each line in a text file, I have the following code:
f = open('./ampo.txt', 'r+')
with open('./ampo.txt') as infile:
for line in infile:
f.insert(0, 'EDF ')
f.close
I get the following error:
'file' object has no attribute 'insert'
Python comes with batteries included:
import fileinput
import sys
for line in fileinput.input(['./ampo.txt'], inplace=True):
sys.stdout.write('EDF {l}'.format(l=line))
Unlike the solutions already posted, this also preserves file permissions.
You can't modify a file inplace like that. Files do not support insertion. You have to read it all in and then write it all out again.
You can do this line by line if you wish. But in that case you need to write to a temporary file and then replace the original. So, for small enough files, it is just simpler to do it in one go like this:
with open('./ampo.txt', 'r') as f:
lines = f.readlines()
lines = ['EDF '+line for line in lines]
with open('./ampo.txt', 'w') as f:
f.writelines(lines)
Here's a solution where you write to a temporary file and move it into place. You might prefer this version if the file you are rewriting is very large, since it avoids keeping the contents of the file in memory, as versions that involve .read() or .readlines() will. In addition, if there is any error in reading or writing, your original file will be safe:
from shutil import move
from tempfile import NamedTemporaryFile
filename = './ampo.txt'
tmp = NamedTemporaryFile(delete=False)
with open(filename) as finput:
with open(tmp.name, 'w') as ftmp:
for line in finput:
ftmp.write('EDF '+line)
move(tmp.name, filename)
For a file not too big:
with open('./ampo.txt', 'rb+') as f:
x = f.read()
f.seek(0,0)
f.writelines(('EDF ', x.replace('\n','\nEDF ')))
f.truncate()
Note that , IN THEORY, in THIS case (the content is augmented), the f.truncate() may be not really necessary. Because the with statement is supposed to close the file correctly, that is to say, writing an EOF (end of file ) at the end before closing.
That's what I observed on examples.
But I am prudent: I think it's better to put this instruction anyway. For when the content diminishes, the with statement doesn't write an EOF to close correctly the file less far than the preceding initial EOF, hence trailing initial characters remains in the file.
So if the with statement doens't write EOF when the content diminishes, why would it write it when the content augments ?
For a big file, to avoid to put all the content of the file in RAM at once:
import os
def addsomething(filepath, ss):
if filepath.rfind('.') > filepath.rfind(os.sep):
a,_,c = filepath.rpartition('.')
tempi = a + 'temp.' + c
else:
tempi = filepath + 'temp'
with open(filepath, 'rb') as f, open(tempi,'wb') as g:
g.writelines(ss + line for line in f)
os.remove(filepath)
os.rename(tempi,filepath)
addsomething('./ampo.txt','WZE')
f = open('./ampo.txt', 'r')
lines = map(lambda l : 'EDF ' + l, f.readlines())
f.close()
f = open('./ampo.txt', 'w')
map(lambda l : f.write(l), lines)
f.close()

How to modify a line in a file using Python

I am trying to do what for many will be a very straight forward thing but for me is just infuriatingly difficult.
I am trying search for a line in a file that contains certain words or phrases and modify that line...that's it.
I have been through the forum and suggested similar questions and have found many hints but none do just quite what I want or are beyond my current ability to grasp.
This is the test file:
# 1st_word 2nd_word
# 3rd_word 4th_word
And this is my script so far:
############################################################
file = 'C:\lpthw\\text'
f1 = open(file, "r+")
f2 = open(file, "r+")
############################################################
def wrline():
lines = f1.readlines()
for line in lines:
if "1st_word" in line and "2nd_word" in line:
#f2.write(line.replace('#\t', '\t'))
f2.write((line.replace('#\t', '\t')).rstrip())
f1.seek(0)
wrline()
My problem is that the below inserts a \n after the line every time and adds a blank line to the file.
f2.write(line.replace('#\t', '\t'))
The file becomes:
1st_word 2nd_word
# 3rd_word 4th_word
An extra blank line between the lines of text.
If I use the following:
f2.write((line.replace('#\t', '\t')).rstrip())
I get this:
1st_word 2nd_wordd
# 3rd_word 4th_word
No new blank line inserted but and extra "d" at the end instead.
What am I doing wrong?
Thanks
Your blank line is coming from the original blank line in the file. Writing a line with nothing in it writes a newline to the file. Instead of not putting anything into the written line, you have to completely skip the iteration, so it does not write that newline. Here's what I suggest:
def wrline():
lines = open('file.txt', 'r').readlines()
f2 = open('file.txt', 'w')
for line in lines:
if '1st_word' in line and '2nd_word' in line:
f2.write((line.replace('# ', ' ')).rstrip('\n'))
else:
if line != '\n':
f2.write(line)
f2.close()
I would keep read and write operations separate.
#read
with open(file, 'r') as f:
lines = f.readlines()
#parse, change and write back
with open(file, 'w') as f:
for line in lines:
if line.startswith('#\t'):
line = line[1:]
f.write(line)
You have not closed the files and there is no need for the \t
Also get rid of the rstrip()
Read in the file, replace the data and write it back.. open and close each time.
fn = 'example.txt'
new_data = []
# Read in the file
with open(fn, 'r+') as file:
filedata = file.readlines()
# Replace the target string
for line in filedata:
if "1st_word" in line and "2nd_word" in line:
line = line.replace('#', '')
new_data.append(line)
# Write the file out again
with open(fn, 'w+') as file:
for line in new_data:
file.write(line)

python: Open file, edit one line, save it as the same file

I want to open a file, search for a specific word, change the word and save the file again. Sounds really easy - but I just can't get it working... I know that I have to overwrite the whole file but only change this one word!
My Code:
f = open('./myfile', 'r')
linelist = f.readlines()
f.close
for line in linelist:
i =0;
if 'word' in line:
for number in arange(0,1,0.1)):
myNumber = 2 - number
myNumberasString = str(myNumber)
myChangedLine = line.replace('word', myNumberasString)
f2 = open('./myfile', 'w')
f2.write(line)
f2.close
#here I have to do some stuff with these files so there is a reason
#why everything is in this for loop. And I know that it will
#overwrite the file every loop and that is good so. I want that :)
If I make it like this, the 'new' myfile file contains only the changed line. But I want the whole file with the changed line... Can anyone help me?
****EDIT*****
I fixed it! I just turned the loops around and now it works perfectly like this:
f=open('myfile','r')
text = f.readlines()
f.close()
i =0;
for number in arange(0,1,0.1):
fw=open('mynewfile', 'w')
myNumber = 2 - number
myNumberasString = str(myNumber)
for line in text:
if 'word' in line:
line = line.replace('word', myNumberasString)
fw.write(line)
fw.close()
#do my stuff here where I need all these input files
You just need to write out all the other lines as you go. As I said in my comment, I don't know what you are really trying to do with your replace, but here's a slightly simplified version in which we're just replacing all occurrences of 'word' with 'new':
f = open('./myfile', 'r')
linelist = f.readlines()
f.close
# Re-open file here
f2 = open('./myfile', 'w')
for line in linelist:
line = line.replace('word', 'new')
f2.write(line)
f2.close()
Or using contexts:
with open('./myfile', 'r') as f:
lines = f.readlines()
with open('./myfile', 'w') as f:
for line in lines:
line = line.replace('word', 'new')
f.write(line)
Use fileinput passing in whatever you want to replace:
import fileinput
for line in fileinput.input("in.txt",inplace=True):
print(line.replace("whatever","foo"),end="")
You don't seem to be doing anything special in your loop that cannot be calculated first outside the loop, so create the string you want to replace the word with and pass it to replace.
inplace=True will mean the original file is changed. If you want to verify everything looks ok then remove the inplace=True for the first run and you will actually see the replaced output instead of the lines being written to the file.
If you want to write to a temporary file, you can use a NamedTemporaryFile with shutil.move:
from tempfile import NamedTemporaryFile
from shutil import move
with open("in.txt") as f, NamedTemporaryFile(dir=".",delete=False) as out:
for line in f:
out.write(line.replace("whatever","foo"))
move("in.txt",out.name)
One problem you may encounter is matching substrings with replace so if you know the word is always followed in the middle of a sentence surrounded by whitespace you could add that but if not you will need to split and check every word.
from tempfile import NamedTemporaryFile
from shutil import move
from string import punctuation
with open("in.txt") as f, NamedTemporaryFile(dir=".",delete=False) as out:
for line in f:
out.write(" ".join(word if word.strip(punctuation) != "whatever" else "foo"
for word in line.split()))
The are three issues with your current code. First, create the f2 file handle before starting the loop, otherwise you'll overwrite the file in each iteration. Third, you are writing an unmodified line in f2.write(line). I guess you meant f2.write(myChangedLine)? Third, you should add an else statement that writes unmodified lines to the file. So:
f = open('./myfile', 'r')
linelist = f.readlines()
f.close
f2 = open('./myfile', 'w')
for line in linelist:
i =0;
if 'word' in line:
for number in arange(0,1,0.1)):
myNumber = 2 - number
myNumberasString = str(myNumber)
myChangedLine = line.replace('word', myNumberasString)
f2.write(myChangedLine)
else:
f2.write(line)
f2.close()

Sorting files and printing out them in alphabetical order in python

I need to write a python script that writes out a list of 10 names, reads the file back and prints out in alphabetical order
I kinda get what I have to do but how I do it is my problem, I don't know if you have to convert the text file into a list then use the sort() function or if I can do it just by splitting the lines.
Here's my code at the moment:
my_file = open("Names.txt", "w")
for i in range(1, 11):
my_file.write(str(input("Please enter a name")) + ", \n")
my_file.close()
my_file = open("Names.txt", "r")
for line in my_file:
print(line)
for line in my_file:
my_file.sort()
my-file.close()
it looks like you are writing to the file fine
How about just
print "".join(sorted(open("Names.txt", "r")))
this works because when you iterate over a file thats open for reading it consumes lines of the file
incidentally that is also the reason your code doesnt work
when you do for line in my_file you consume the file and it leaves you at the end of the file
then when you do it a second time you are already at the end of the file so you never go inside the second loop
in addition to that it looks like you are trying to sort each name , (ie Susan -> Sansu)
Try this one :
my_file = open("Names.txt", "w")
for i in range(1, 11):
my_file.write(str(input("Please enter a name")) + ", \n")
my_file.close()
my_file = open("Names.txt", "r")
for line in sorted(my_file):
print line
my-file.close()
with open("Names.txt", "a+") as f: # use with to open files as it closes them automatically
for i in range(1, 11):
f.write("{} \n".format(str(input("Please enter a name"))))
f.seek(0) # go back to start of file
for line in f: # print each name
print(line)
f.seek(0) # go back to start again
lines = sorted(f.readlines()) # sort the names
with open("Names.txt", "w") as f1: # write names in sorted order
for line in lines:
f1.write(line)

Categories