Function that takes file as input - python

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.

Related

FileNotFoundError: [Errno 2] No such file or directory for different opening types

I have two almost similar ways to open a file:
first one works fine:
filename = 'RN6531_flat_20ums_3.pr'
pr_file = open(filename,'r')
print(pr_file.readlines())
pr_file = pr_file.close
the second one should do the same
filename = 'RN6531_flat_20ums_3.pr'
with open('filename') as pr_file:
print(pr_file.readlines())
pr_file = pr_file.close
but actually delivers the error message
FileNotFoundError: [Errno 2] No such file or directory: 'filename'
What am I doing wrong? I'm learning coding with python at the moment and don't see the difference. The paths are the same, the file exists, but only one way works as expected.
Fix some typo, also you don't have to close file manually context manager will do it for you
filename = 'RN6531_flat_20ums_3.pr'
with open(filename, 'r') as pr_file:
print(pr_file.readlines())

Passing function to new function to read file

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")

File or directory not found even though it exists

this is my code to open a file and get the text from it :
f = open("C:/Users/muthaharsh/Documents/Harsh/News
Project/Part3/Testing_purposes/Downloads3/Are-you-being-churned-,-
Mint.txt","r+")
text = f.readlines()
print(text)
but i keep getting the error :
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/muthaharsh/Documents/Harsh/News Project/Part3/Testing_purposes/Downloads3/Are-you-being-churned-,-Mint.txt'
What code do i write to be able to do this ?
Thanks in advance ...
It's the whitespace in the path to file. Either use
r"C:/Users/muthaharsh/Documents/Harsh/News Project/Part3/Testing_purposes/Downloads3/Are-you-being-churned-,-Mint.txt"
or remove the whitespace in the filepath.
If you are running the code on windows add r before your filepath string.
Another way is that you can provide your input file as system arguments.
import sys
file_name = sys.argv[1]
with open(file_name, 'r') as f1:
file_text = f1.read()
print(file_text)
eg: python program for reading the file
you can run the code considering script is saved as readFile.py:
D:\Programs>python readFile.py D:\test.txt
output: This is a sample file
Here is the text

Define a class to write into a file in Python

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.

fileinput error (WinError 32) when replacing string in a file with Python

After looking for a large amount of time, I still can't seem to find an answer to my problem (I am new to python).
Here is what I'm trying to do :
Prompt the user to insert an nlps version and ncs version (both are just server builds)
Get all the filenames ending in .properties in a specified folder
Read those files to find the old nlps and ncs version
Replace, in the same .properties files, the old nlps and ncs versions by the ones given by the user
Here is my code so far :
import glob, os
import fileinput
nlpsversion = str(input("NLPS Version : "))
ncsversion = str(input("NCS Version : "))
directory = "C:/Users/x/Documents/Python_Test"
def getfilenames():
filenames = []
os.chdir(directory)
for file in glob.glob("*.properties"):
filenames.append(file)
return filenames
properties_files = getfilenames()
def replaceversions():
nlpskeyword = "NlpsVersion"
ncskeyword = "NcsVersion"
for i in properties_files:
searchfile = open(i, "r")
for line in searchfile:
if line.startswith(nlpskeyword):
old_nlpsversion = str(line.split("=")[1])
if line.startswith(ncskeyword):
old_ncsversion = str(line.split("=")[1])
for line in fileinput.FileInput(i,inplace=1):
print(line.replace(old_nlpsversion, nlpsVersion))
replaceversions()
In the .properties files, the versions would be written like :
NlpsVersion=6.3.107.3
NcsVersion=6.4.000.29
I am able to get old_nlpsversion and old_ncsversion to be 6.3.107.3 and 6.4.000.29. The problem occurs when I try to replace the old versions with the ones the user inputed. I get the following error :
C:\Users\X\Documents\Python_Test>python replace.py
NLPS Version : 15
NCS Version : 16
Traceback (most recent call last):
File "replace.py", line 43, in <module>
replaceversions()
File "replace.py", line 35, in replaceversions
for line in fileinput.FileInput(i,inplace=1):
File "C:\Users\X\AppData\Local\Programs\Python\Python36-
32\lib\fileinput.py", line 250, in __next__
line = self._readline()
File "C:\Users\X\AppData\Local\Programs\Python\Python36-
32\lib\fileinput.py", line 337, in _readline
os.rename(self._filename, self._backupfilename)
PermissionError: [WinError 32] The process cannot access the file because it
is being used by another process: 'test.properties' -> 'test.properties.bak'
It may be that my own process is the one using the file, but I can't figure out how to replace, in the same file, the versions without error. I've tried figuring it out myself, there are a lot of threads/resources out there on replacing strings in files, and i tried all of them but none of them really worked for me (as I said, I'm new to Python so excuse my lack of knowledge).
Any suggestions/help is very welcome,
You are not releasing the file. You open it readonly and then attempt to write to it while it is still open. A better construct is to use the with statement. And you are playing fast and loose with your variable scope. Also watch your case with variable names. Fileinput maybe a bit of overkill for what you are trying to do.
import glob, os
import fileinput
def getfilenames(directory):
filenames = []
os.chdir(directory)
for file in glob.glob("*.properties"):
filenames.append(file)
return filenames
def replaceversions(properties_files,nlpsversion,ncsversion):
nlpskeyword = "NlpsVersion"
ncskeyword = "NcsVersion"
for i in properties_files:
with open(i, "r") as searchfile:
lines = []
for line in searchfile: #read everyline
if line.startswith(nlpskeyword): #update the nlpsversion
old_nlpsversion = str(line.split("=")[1].strip())
line = line.replace(old_nlpsversion, nlpsversion)
if line.startswith(ncskeyword): #update the ncsversion
old_ncsversion = str(line.split("=")[1].strip())
line = line.replace(old_ncsversion, ncsversion)
lines.append(line) #store changed and unchanged lines
#At the end of the with loop, python closes the file
#Now write the modified information back to the file.
with open(i, "w") as outfile: #file opened for writing
for line in lines:
outfile.write(line+"\n")
#At the end of the with loop, python closes the file
if __name__ == '__main__':
nlpsversion = str(input("NLPS Version : "))
ncsversion = str(input("NCS Version : "))
directory = "C:/Users/x/Documents/Python_Test"
properties_files = getfilenames(directory)
replaceversions(properties_files,nlpsversion,ncsversion)

Categories