Saturday, June 29, 2019

How to Python Check If File or Directory Exists

There are different ways to verify a file or directory exists, using functions as listed below:

1. os.path.exists()
2. os.path.isfile()
3. os.path.isdir()

4. pathlibPath.exists()

os.path.exists()

Using path.exists you can quickly check that a file or directory exists. Here are the steps
Steps 1) Before you run the code, it is important that you import the os.path module.
import os.path
from os import path
Steps 2) Now, use the path.exists() function to check whether a File Exists.
path.exists("guru99.txt")
Steps 3) Here is the complete code
import os.path
from os import path

def main():

   print ("file exist:"+str(path.exists('guru99.txt')))
   print ("File exists:" + str(path.exists('career.guru99.txt')))
   print ("directory exists:" + str(path.exists('myDirectory')))

if __name__== "__main__":
   main()
In our case only file guru99.txt is created in the working directory
Output:
File exists: True
File exists: False
directory exists: False

os.path.isfile()

We can use the isfile command to check whether a given input is a file or directory.
import os.path
from os import path

def main():

 print ("Is it File?" + str(path.isfile('guru99.txt')))
 print ("Is it File?" + str(path.isfile('myDirectory')))
if __name__== "__main__":
 main()
Output:
Is it File? True
Is it File? False

os.path.isdir()

If we want to confirm that a given path points to a directory, we can use the os.path.dir() function
import os.path
from os import path

def main():

   print ("Is it Directory?" + str(path.isdir('guru99.txt')))
   print ("Is it Directory?" + str(path.isdir('myDirectory')))

if __name__== "__main__":
   main()
Output:
Is it Directory? False
Is it Directory? True

pathlibPath.exists() For Python 3.4

Python 3.4 and above versions have pathlib Module for handling with file system path. It used object-oriented approach to check if file exist or not.
import pathlib
file = pathlib.Path("guru99.txt")
if file.exists ():
    print ("File exist")
else:
    print ("File not exist")

Output:
File exist
Complete Code
Here is the complete code
import os
from os import path

def main():
    # Print the name of the OS
    print(os.name)
#Check for item existence and type
print("Item exists:" + str(path.exists("guru99.txt")))
print("Item is a file: " + str(path.isfile("guru99.txt")))
print("Item is a directory: " + str(path.isdir("guru99.txt")))

if __name__ == "__main__":
    main()
Output:
Item exists: True
Item is a file: True
Item is a directory: False
Summary:
  • Use path.exists to check whether a File Exists
  • Use path.isfile and path.isdir to check whether a path is File or Directory respectively
  • In Python 3.4 and above versions use pathlib Module to check a file exists.

Python File Handling: Create, Open, Append, Read, Write

In Python, there is no need for importing external library to read and write files. Python provides an inbuilt function for creating, writing and reading files.

How to Create a Text File

With Python you can create a .text files (guru99.txt) by using the code, we have demonstrated here how you can do this
Step 1)
 f= open("guru99.txt","w+")
  • We declared the variable f to open a file named textfile.txt. Open takes 2 arguments, the file that we want to open and a string that represents the kinds of permission or operation we want to do on the file
  • Here we used "w" letter in our argument, which indicates write and the plus sign that means it will create a file if it does not exist in library
  • The available option beside "w" are "r" for read and "a" for append and plus sign means if it is not there then create it
Step 2)
for i in range(10):
     f.write("This is line %d\r\n" % (i+1))
  • We have a for loop that runs over a range of 10 numbers.
  • Using the write function to enter data into the file.
  • The output we want to iterate in the file is "this is line number", which we declare with write function and then percent d (displays integer)
  • So basically we are putting in the line number that we are writing, then putting it in a carriage return and a new line character
Step 3)
 f.close() 
  • This will close the instance of the file guru99.txt stored
Here is the result after code execution
Python FILE Tutorial: Create, Append, Read, Write
When you click on your text file in our case "guru99.txt" it will look something like this
Python FILE Tutorial: Create, Append, Read, Write

How to Append Data to a File

You can also append a new text to the already existing file or the new file.
Step 1)
f=open("guru99.txt", "a+")
Once again if you could see a plus sign in the code, it indicates that it will create a new file if it does not exist. But in our case we already have the file, so we are not required to create a new file.
Step 2)
for i in range(2):
     f.write("Appended line %d\r\n" % (i+1))
This will write data into the file in append mode.
Python FILE Tutorial: Create, Append, Read, Write
You can see the output in "guru99.txt" file. The output of the code is that earlier file is appended with new data.
Python FILE Tutorial: Create, Append, Read, Write

How to Read a File

Not only you can create .txt file from Python but you can also call .txt file in a "read mode"(r).
Step 1) Open the file in Read mode
 f=open("guru99.txt", "r")
Step 2) We use the mode function in the code to check that the file is in open mode. If yes, we proceed ahead
 if f.mode == 'r':
Step 3) Use f.read to read file data and store it in variable content
 contents =f.read()
Step 4) print contents
Here is the output
Python FILE Tutorial: Create, Append, Read, Write

How to Read a File line by line

You can also read your .txt file line by line if your data is too big to read. This code will segregate your data in easy to ready mode
Python FILE Tutorial: Create, Append, Read, Write
When you run the code (f1=f.readlines()) for reading the file or document line by line, it will separate each line and present the file in a readable format. In our case the line is short and readable, the output will look similar to the read mode. But if there is a complex data file which is not readable, this piece of code could be useful.

File Modes in Python

ModeDescription
'r'This is the default mode. It Opens file for reading.
'w'This Mode Opens file for writing. 
If file does not exist, it creates a new file.
If file exists it truncates the file.
'x'Creates a new file. If file already exists, the operation fails.
'a'Open file in append mode. 
If file does not exist, it creates a new file.
't'This is the default mode. It opens in text mode.
'b'This opens in binary mode.
'+'This will open a file for reading and writing (updating)

Here is the complete code
Python 2 Example
def main():
     f= open("guru99.txt","w+")
     #f=open("guru99.txt","a+")
     for i in range(10):
         f.write("This is line %d\r\n" % (i+1))
     f.close()   
     #Open the file back and read the contents
     #f=open("guru99.txt", "r")
     #   if f.mode == 'r': 
     #     contents =f.read()
     #     print contents
     #or, readlines reads the individual line into a list
     #fl =f.readlines()
     #for x in fl:
     #print x
if __name__== "__main__":
  main()
Python 3 Example
def main():
    f= open("guru99.txt","w+")
    #f=open("guru99.txt","a+")
    for i in range(10):
         f.write("This is line %d\r\n" % (i+1))
    f.close()
    #Open the file back and read the contents
    #f=open("guru99.txt", "r")
    #if f.mode == 'r':
    #   contents =f.read()
    #    print (contents)
    #or, readlines reads the individual line into a list
    #fl =f.readlines()
    #for x in fl:
    #print(x)
if __name__== "__main__":
  main()
Summary
  • Python allows you to read, write and delete files
  • Use the function open("filename","w+") to create a file. The + tells the python compiler to create a file if it does not exist
  • To append data to an existing file use the command open("Filename", "a")
  • Use the read function to read the ENTIRE contents of a file
  • Use the readlines function to read the content of the file one by one.




How To Create JSON Objects Using C# Code (JSON Creation Part 1)

Introduction To JSON

In today’s busy world, most of the real-time communication between the systems are handled through JSON. It’s quite obvious that with the increasing popularity JSON has replaced XML to a great extent. JSON has its own set of advantages like it’s easy to read text format and lightweight structure.
Many people are now replacing XML with JSON for data exchange communications. Not long ago, programmers used to use XML for communication between service applications like WCF or web service. But as web API gained its momentum, users started exploring JSON as an alternate data serializing format.
JSON is also known as JavaScript Object Notion, is lightweight, text-based data communication format which is widely used for real-time data communication between a web server and the application. Its compatibility with the numerous programming languages is an added advantage for JSON.
Being a text-based language it is easier to read by the user and at the same time, it can be easily analyzed by machine. For more information and details about JSON, please refer to our previous tutorial on JSON Introduction.

Pre-Requisite

There are numerous ways to create a JSON, we can either use the native .Net library’s own class for serializing data in JSON format or we can make use of any other third party element. In this tutorial, we will use NewtonSoft serialization library for serializing the JSON structure.
Firstly, we need to download and install the Newtonsoft package using the NuGet package manager present in the visual studio.

The Setup

Before we start writing the code for serialization, we will have to set up the visual studio and install the Newtonsoft package.
Install visual studio on your machine, any version of the Visual Studio will do (Visual Studio Community edition is freely available). Once, installed open the visual studio and create a new project. Select Visual C# from the left-hand panel and select console application from the associated list displayed.
Give a proper meaningful name to your project and provide the location. Here, as we are going to write a simple program to create a JSON, I have given it a name like “jsonCreate”. You can provide any name that you are comfortable with or which is easier for you to identify your program.
Create a new project
Json Setup
Once everything is set click on ok button.
A new project will be created and it will look as the image given below:
JSON New Project
Once the project has been created, we will add json.net reference to the project. To add the reference, right click on the solution in the right panel and click on the “Manage NuGet Packages”option from the menu list.
Adding Reference
Click on the install button to install, Json.NET. It will begin downloading the Json.Net package. Once the download is complete it will be installed and a green tick will appear on Json.Net.
Go to reference in the solution explorer, where you will find that a reference for Newtonsoft.json has already been added there.
Reference In Solution Explorer
So, with the creation of a project and addition of the newtonsoft.json our setup is complete. Now, we can start writing the code for creating JSON.

Writing The Code For Your First JSON

We have already added the reference for the Newtonsoft to our solution. Now, we can start working on our very first code to serialize and create a JSON. We will start with a simple JSON structure and later let's gradually move towards more complex structures while discussing each line of the code and its functionality in details.
We will try to keep this tutorial as simple and generic as possible. However, readers are required to have a little or basic knowledge of c# programming before proceeding with this tutorial.
Let’s say we want to create an employee JSON with the following employee data.
Creating Employee JSON
For structuring a JSON, let’s first add a new class to our project.
Adding New Class
I am calling this class as “Employee”, you can give any relevant name for your class. Once you have created the class, it will get added inside the current namespace.
Added New Class
Once the class has been created, let’s define the variable objects in the new class.
Defining Variable
Here, we have assigned public access to our objects. This will ensure that we can access these objects from any other class inside the namespace. This will be quite helpful while we use JSON serialize.
Further keeping a similar set of data in a single class makes it easier for the user to change the data on the go or perform any operations on the data. This will also help in maintaining the data integrity as any changes in the objects in any class will be restricted to that class only. The user will not have to make changes to the project.
We have also assigned the data type for each of the variables that we have defined here. Now, let’s go back to our main method.
First, we will define the employee class as an object in our main method.
Employee emp = new Employee();
Next, we will serialize the class object that we defined into JSON using JsonConvert.SerializeObject. Let’s store the serialized data inside a string variable.
string JSON result = JsonConvert.SerializeObject(emp);
Now, we have serialized the data into JSON structure, but we will need to save the data somewhere, so we will provide a path. To make it simpler we will store the location path into a string variable to use it later.
string path = @"D:\json\employee.json";
Now, to save the JSON at the given location we will use StreamWriter to save the .JSON file at the given path.
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(JSONresult.ToString());
tw.Close();
}
Overall code structure for the main method will look like this:
Main Method
As shown the StreamWriter will keep on placing the newly created file at the given location. But, if the location already contains a file with the same name then what will happen? So, to handle this kind of situation we will write a simple condition to check whether the given file already exists at the particular location, if yes then we will first delete it then save a new file.
To do this we will simply enclose the StreamWriter with an if condition. We will use File. Exists on the path that we provided earlier to validate if the file is already present at the given location. If it is present then our code will delete the first one and then it will create a new one.
If the condition is not true, i.e. the file is not present then it will directly create the file at the given path.
Adding StreamWriter
So, everything is set now. Let's build our project first. Once the build is complete and we don’t have any compilation errors remaining then we are good to go. Just click on the Start button at the top and the program will be executed. The program will create our first .json at the given location.
Now, we will navigate to the location we have provided in the code and we can see an employee .jsonfile presents there.
Json File
Open the JSON file to view the content.
Json Input File
All the keys that we provided in the employee class are present in the JSON but the values are null for string and it's “0” for integer.
Let’s now try to add values to the keys in the JSON.
There are numerous ways by which a value can be assigned to its key using the code but as we have just pitched into the initial stage of the JSON creation we will directly add the values to the variables in the employee class itself.
Go to the employee class and assign values directly to the variables. This will allow the class object that we created in the main method to pick both the key and values together directly from the class.
1class Employee
2{
3public string FirstName = "Sam";
4public string LastName = "Jackson";
5public int employeeID = 5698523;
6public string Designation = "Manager";
7}
Now, we will save the project and build it again. Once the build is complete we will run the project. Now let's navigate to the path where the JSON is being saved, we will find that a new JSON has been created at the location.
Open the new file. It will now have all the key-value pairs as assigned in our code.
Open New File
Finally, we have created a JSON file but let’s validate if the JSON that we have created has a valid structure or not. To validate this we will go here.
Just copy the data from the JSON file and paste it into the text area of the site.
Json File
After pasting the data click on the “Validate JSON” button. This will arrange the data and validate if the JSON we have provided is valid or not.
Validate JSON
Congrats we have created our first valid JSON file programmatically.
An exercise for you:
Create a Student JSON with the following keys: Name, Class, Subjects, and Roll No.
The name is a string, Class and Roll No. will be integer and Subject will be an Array.
Pass the appropriate values to each key.

Conclusion

In this tutorial, we learned how to create simple JSON Objects using a C# programming language with Visual Studio.
We also learned to differentiate different data sets into different classes. The JSON structure that we created in this tutorial was one of the most basic formats.

No String Argument Constructor/Factory Method to Deserialize From String Value

  In this short article, we will cover in-depth the   JsonMappingException: no String-argument constructor/factory method to deserialize fro...