In this code I tried to define a class which will write into a file.In the init method the name of the file is passed.I also defined a method named "write" to write to the file.Then I created an instance of the class and passed the value of the file name.After that, I called the write method and passed the message to write in the file.At last, I checked if the file is created and if the file has the message.Here's the code:
class Logfile(object):
def __init__(self,file_name):
self.file_name = file_name
def write(self,msg):
with open('self.file_name','w') as myFile:
myFile.write(msg)
log = Logfile('myNewFile.txt')
log.write("this is a log file.")
with open('myNewFile.txt','r') as readFile:
read_file = readFile.read()
for line in read_file:
print(line)
But, it shows an error:
FileNotFoundError: [Errno 2] No such file or directory: 'myNewFile.txt'
This python code is saved in a desktop folder called "My Folder".And when I go there, there is really no such file named "myNewFile.txt".
But, if I run the program with the checking part of the code, I mean,this part:
with open('myNewFile.txt','r') as readFile:
read_file = readFile.read()
for line in read_file:
print(line)
then, there is no error but still the "myNewFile.txt" is not created.
Can you please help me?
In the write method you should write :
with open(self.file_name, ‘w’) as my_file
because self.file_name is already a string.
log = Logfile('myNewFile.txt')
log.write("this is a log file.")
with open('myNewFile.txt','r') as readFile:
read_file = readFile.read()
for line in read_file:
print(line)
You could always try to open the file using with open(log) because you have already made the .txt file a variable. I have never tried this and have little experience with this type of code, but it could be worth a shot.
Related
I tried running this code in python. I ensured:
The .txt file was in the same file as the code file and the file name was "random.txt" saved in .txt format
file = input ('Enter File:')
if len(file) < 1 : file = 'random.txt'
fhan = open(file)
print (fhan)
My command prompt returned me <_io.TextIOWrapper name='random.txt' mode='r' encoding='cp1252'> with no traceback. I don't know how to get the file to open and print the content
Open a file, and print the file content:
with open('./demo.txt', 'r') as file:
txt = file.read()
print(txt)
fhan is a file handle, so printing it simply prints the results of calling its repr method, which shows what you see. To read the entire file, you can call fhan.read().
It's also good practice to use a with statement to manage resources. For example, your code can be written as
file = input('Enter File:')
if not file: # check for empty string
file = 'random.txt'
with open(file, 'r') as fhan: # use the `with` statement
print(fhan.read())
The benefit of this syntax is that you'll never have to worry about forgetting to close the file handle.
I am trying to write a program that will open a file and print its contents. I am having some trouble with defining it I suppose? If it is not telling me that "path" is not defined, then it is telling me that "new_dir" is not defined.
Here is the code:
import pathlib
def prog_info():
print("This program will open a file, read and print its contents.")
print("-----------------------------------------------------------")
prog_info()
file_path = new_dir / "numbers.txt"
file_path.parent.mkdir()
file_path.touch()
with path.open("numbers.txt", mode="r", encoding="utf-8") as file:
for line in file:
print(line.strip())
The file is going to have three numbers that will be printed:
22
14
-99
with open("filename or location", 'r') as my_file:
for line in my_file:
print(line)
I hope this helped you.
You don't need mode, and you don't need the import. All you need is the code provided
I have a problem with reading some massive text-files.
I firstly define reading my text file as follows:
def reader(filename):
with open(filename, encoding='latin-1') as thefile:
contentsofthefile = f.read()
return contentsofthefile
Now I want to have another function, that uses the above function, such as:
def remover(filename):
a = reader(filename)
for line in a:
do this
This yields the following problem:
OSError: [Errno 63] File name too long: 'In search of lost time - CHAPTER///1 \nThe characters, plotlines, ...."
It seems that it attempts to read the entire file as the filename?
If you're going to process the file line by line, there's no reason not to read the file line by line as well. You don't really need a reader function, but it can be as simple as
def reader(filename):
return open(filename, encoding='latin1=1')
Then to use reader inside remover:
def remover(filename):
with reader(filename) as f:
for line in f:
...
remover("somefile.txt")
def readfile(file):
edges = [] # to contain tuples of all edges
with open(file) as f:
for line in f:
I'm trying to pass in a text file called file, then read it, but it doesn't work. Even if I cast file to a string it doesn't work.
Python says
with open(file) as f: IOError: [Errno 22] invalid mode ('r') or
filename: "<type 'file'>"
How do I open a file, passed to open as a variable?
Rename file by filename as file is a built-in name for python :
def readfile(filename):
edges = [] # to contain tuples of all edges
with open(filename) as f:
for line in f:
open() use 'r' as default mode.
First of all , as file is a type in python you shouldn't use it as a variable name or file name , second you need to put the file name in quote inside the open function and note that open function use read mod as default ! :
with open('file_name.txt','r') as f:
for line in f:
I want to define a function that takes a file name, and runs the file through some code. I have completed the latter part, but I'm stuck at the first part. Here is where I'm having trouble:
def function(inputfilename):
file = open("inputfilename","r")
example input and the error I get:
>>>function("file.csv")
FileNotFoundError: [Errno 2] No such file or directory: 'inputfilename'
How can I fix this?
You are trying to open a file with inputfilename name.
Replace:
file = open("inputfilename", "r")
with:
file = open(inputfilename, "r")
Also, consider using with context manager while working with files.