Text file opening in python - python

Could someone give me some guidance on how you would get the contents of your text file on my python code without opening up the text file in another window?
Just point me in the right direction on how I should do it (No need for solutions)

with open(workfile, 'r') as f:
for line in f:
print line
If you don't use the context manager (the with statement) you will need to explicitly call f.close(), for example:
f = open('workfile', 'r')
line = f.readline()
print line
f.close()

file = open("your_file.txt", "r")
file.read()

Related

Is there way to close a file in python, without a file object?

I can't close this file, as the file is directly fed into the 'lines'-list.
I have tried closing with command lines.close() but it doesn't work.
def readfile():
lines = [line.rstrip('\n') for line in open('8ballresponses.txt', 'r')]
print(random.choice(lines))
I don't get an error, but i want to be able to close the file.
Instead of file object, lines is a list , so you can't close it. And you should store file object open('8ballresponses.txt', 'r') with a variable for closing it later:
def readfile(file_path):
test_file = open(file_path, 'r')
lines = [line.rstrip('\n') for line in test_file]
test_file.close()
print(random.choice(lines))
Or simply use with "to close a file in python, without a file object":
def readfile(file_path):
with open(file_path, 'r') as test_file:
lines = [line.rstrip('\n') for line in test_file]
print(lines)
you can use with open command. this will automatically handle all the test cases failure etc. (inbuild try except and finally in python)
below is example similiar to your code
import random
def readfile():
lines = []
with open(r"C:\Users\user\Desktop\test\read.txt",'r') as f:
lines = f.readlines()
print(random.choice(lines))
You can use try and finally block to do the work.
For example :
def readfile():
file = open('8ballresponses.txt', 'r')
try:
lines = [line.rstrip('\n') for line in file]
print(random.choice(lines))
finally:
file.close()
In this post
"When the with ends, the file will be closed. This is true even if an exception is raised inside of it."
You manually invoke the close() method of a file object explicitly or implicitly by leaving a with open(...): block. This works of course always and on any Python implementation.
Use with this will close implicitly after the block is complete
with open('8ballresponses.txt', 'r') as file:
lines = [ line.rstrip("\n") for line in file ]

how to open a file using strings of other file in python?

I have 1000 files, and the name of these are "numbers", for example, 2323.csv.
I have these name in a file called 1.txt.
Now I want to open these files one by one in python, using 1.txt to open them.
How can I do this?
Why not this?
with open('1.txt', 'r') as listFile:
for line in listFile:
with open(line.rstrip(), 'r') as individualFile:
# do stuff
Roughly and very basic but understandable code (no error handling).
with open('1.txt', 'r') as f:
for line in f.readlines(): # This assumes each line has a number
with open('.'.join([line, 'csv']) as cf:
file_content = cf.readlines()
print(file_content)

Appends text file instead of overwritting it

The context is the following one, I have two text file that I need to edit.
I open the first text file read it line by line and edit it but sometimes when I encounter a specific line in the first text file I need to overwritte content of the the second file.
However, each time I re-open the second text file instead of overwritting its content the below code appends it to the file...
Thanks in advance.
def edit_custom_class(custom_class_path, my_message):
with open(custom_class_path, "r+") as file:
file.seek(0)
for line in file:
if(some_condition):
file.write(mu_message)
def process_file(file_path):
with open(file_path, "r+") as file:
for line in file:
if(some_condition):
edit_custom_class(custom_class_path, my_message)
In my opinion, simultaneously reading and modifying a file is a bad thing to do. Consider using something like this. First read the file, make modifications, and then overwrite the file completely.
def modify(path):
out = []
f = open(path)
for line in f:
if some_condition:
out.append(edited_line) #make sure it has a \n at the end
else:
out.append(original_line)
f.close()
with open(path,'w') as f:
for line in out:
f.write(line)

Printing a .txt File Python

I need some help Im trying to display the text files contents (foobar) with this code
text = open('C:\\Users\\Imran\\Desktop\\text.txt',"a")
rgb = text.write("foobar\n")
print (rgb)
text.close()
for some reason it keeps displaying a number. If anyone could help that would be awesome, thanks in advance
EDIT: I am Working with Python 3.3.
Print the contents of the file like this:
with open(filename) as f:
for line in f:
print(line)
Use with to ensure that the file handle will be closed when you are finished with it.
Append to the file like this:
with open(filename, 'a') as f:
f.write('some text')
# Open a file
fo = open("foo.txt", "r+")
str = fo.read();
print "Read String is : ", str
# Close opend file
fo.close()
More: http://www.tutorialspoint.com/python/python_files_io.htm
You are printing the number of written bytes. That won't work. Also you might need to open the file as RW.
Code:
text = open('...', "a")
text.write("foo\n")
text = open('...', "r")
print text.read()
If you want to display the contents of the file open it in read mode
f=open("PATH_TO_FILE", 'r')
And then print the contents of file using
for line in f:
print(line) # In Python3.
And yes, don't forget to close the file pointer f.close() after you finish the reading

how to make a .text file in terminal python3.33

I was wondering how to make a .text file so I can put words in it and then in my program open the file. I just need to know how to make a .text file!
Anyone know why my code won't open my .txt file when I try to run it?
def readWords(filename):
words = []
wordFile = open(words.txt, "r")
for line in wordFile:
line = line.upper()
words.extend(string.split(line))
wordFile.close()
return words
with open('myfile.txt', 'w') as f:
f.write('potato')
Opening a file in write mode will create it for you if it doesn't already exist:
with open("/path/to/file.txt", "w") as myfile:
# Do whatever
In the above code, myfile will be the file object.
Here is a reference on open and one on with.

Categories