How to open a text file in python? - python-3.x

I try to do the following,
file = open('test.txt', 'w+')
item = "hello"
file.write(item)
print(file)
When I run this program I get the following output,
<_io.TextIOWrapper name='test.txt' mode='w+' encoding='cp1252'>
Is there a way to open and then write in the file and then save it so I can use that new file somewhere else? Even though I have something written in the file, I still get this output.

f = open("file.txt",'r+')
lines = f.readlines()
f.writelines(lines)
f.close()

Related

Deleting from files

(I have only been learning Python3 for about 2 weeks now. So if you could keep the answer as ELI5 as possible that would be great)
In this image, I have first read the file and then second zeroed the file and recreated it while removing all the lines containing 'Ford'
This image shows the contents of the file that I wish to be printed out
The problem I have is that the result is being printed as 'none'.
How would I make it so this program prints out what is inside the file?
Thanks!
code below
def delete_ford(path, term):
buffer = []
with open(path, "r") as file:
for line in file:
buffer.append(line.strip())
with open(path, "w") as file:
for line in buffer:
if line != term:
file.write(line + "\n")
with open(path, "r") as file:
for line in file:
buffer.append(line.strip())
print(buffer)
print(delete_ford("cars.txt", "Ford"))
As #John Zwinck and #Albert Alberto pointed out, your function has nothing to return as the output is written to the file.
If you want it simply to print out the contents of the file, you can do this when you're writing to it like this:
with open(path, "w") as file:
for line in buffer:
if line != term:
file.write(line + "\n") # This is what is being written to the file
print(line) # So this will effectively output the contents of the file
Hope this does what you want it to

Pass a file with filepaths to Python in Ubuntu terminal to analyze each file?

I have a text file with file paths:
path1
path2
path3
...
path100000000
I have my python script app.py that should run on each file (path1, path2 ...)
Please advise what is the best way to do it?
Should I just get it as argument, and then:
with open(input_file, "r") as f:
lines = f.readlines()
for line in lines:
main_function(line)
Yes that should work, except readlines() doesn't remove newline characters.
with open(input_file, "r") as f:
lines = f.readlines()
for line in lines:
main_function(line.strip())
**Note: The above code assumes the file is in the same directory as the python script file.
You are using context managers. Hence, place the code inside the context.
So according to your comment,
If you want to pass filename where you will read the file contents in the main_function, then the above code will work.
If you want to read the file and then pass the file contents, then you will have to modify the above code to first read the content and then pass it to the function
with open(input_file, "r") as f:
lines = f.readlines()
for line in lines:
main_function(open(line.strip(), "r").read())
**Note: the above function will read the whole file as a single string (text)

How to edit a line in a notepad file using python

I am trying to edit a specific line of a notepad file using Python 3. I can read from any part of the file and write to the end of it, however whenever I have tried editing a specific line, I am given the error message 'TypeError: 'int' object is not subscriptable'. Does anybody know how I could fix this?
#(This was my first attempt)
f = open('NotepadTester.txt', 'w')
Edit = input('Enter corrected data')
Line = int(input('Which line do you want to edit?'))
f.write(Edit)[Line-1]
f.close()
main()
#(This was my second attempt)
f = open('NotepadTester.txt', 'w')
Line = int(input('Which line do you want to edit?'))
Edit = input('Enter corrected data')
f[Line-1] = (Edit)
main()
you can't directly 'edit' a line in a text file as far as I know. what you could do is read the source file src to a variable data line-by-line, edit the respective line and write the edited variable to another file (or overwrite the input file) dst.
EX:
# load information
with open(src, 'r') as fobj:
data = fobj.readlines() # list with one element for each text file line
# replace line with some new info at index ix
data[ix] = 'some new info\n'
# write updated information
with open(dst, 'w') as fobj:
fobj.writelines(data)
...or nice and short (thanks to Aivar Paalberg for the suggestion), overwriting the input file (using open with r+):
with open(src, 'r+') as fobj:
data = fobj.readlines()
data[ix] = 'some new info\n'
fobj.seek(0) # reset file pointer...
fobj.writelines(data)
You should probably load all the lines into memory first, modify it from there, and then write the whole thing to a file.
f = open('NotepadTester.txt', 'r')
lines = f.readlines()
f.close()
Which_Line = int(input('Which line do you want to edit? '))
Edit = input('Enter corrected data: ')
f = open("NotepadTester.txt",'w')
for i,line in enumerate(lines):
if i == Which_Line:
f.writelines(str(Edit)+"\n")
else:
f.writelines(line)
f.close()

write a program that reads the content of hoilday.txt, one line at a time

I have to do this Coding Challenge on python 3.5.2.
So far here is my code:
file = open("holiday text",'r')
contents = file.read
print(contents)
file.close()
This should do the trick. Note that if the text file isn't in the same folder as the python (eg C:/Python35-32) you should specify the whole path, except if it's for some online challenge where you just provide the text file.
file = open("holiday text.txt",'r')
contents = file.read()
file.close()
print(contents)
Another way is to use the with statement which automatically opens/closes the file appropriately, like so:
with open("holiday text.txt",'r') as file:
contents = file.read()
print(contents)
If it helped, please press the arrow button for accepted answer.

problems with reading a text file in python

Hi I'm trying to write a basic function that prints the contents from a textfile. The code I used is:
def open_my_file(input_file):
in_file = open(input_file, "r")
contents = in_file.read()
file.close()
word_list = contents.split(',')
print(word_list)
when I try running the program, it says syntax error.
Can someone help, please?
You use in_file when you open & read, but file when you close. That wouldn't be a syntax error, though.
When you're opening the file you're declaring the file with the name in_file, when you close the file you're saying file.close(), because you haven't declared any variable with the name file the python program gives you an SyntaxError.
Change file.close() to in_file.close()

Resources