0

I'm trying to learn python 3. I was going through the exercises of File Handling. I'm having an issue with my code, when i try to write a file, it doesn't make any file sometimes and sometimes a file is generated but when i try to read it. It shows blank output. Most of time it give some sort of syntax error, while i'm using the basics and simple code. But sometime instead of using run in terminal, when i click on run code, it produces the output but still gives error on terminal.

I've tried doing it with, With and casual method. I've looked up on google for the issue but i didn't got any specific answer. I've tried to follow the python documentation and their code.

I've tried both open with method and casual method but i'm still facing this issue.

  ```
  with open('text.txt','w+')as f:
      f.write("Hell Men")
  with open('text.txt','r+')as f:
      print(f.read())
```

Also tried it this way:

file=open('word.txt','w')
file.write("Python you are making me mad")
file.read()

I was expecting the content of the file in output, but instead it shows blank on clicking run code.

Error: invalid syntax

4 Answers 4

1

@Viswamedha Nalabotu Not necessary. you can read and write both. Yeah but using close is better as it can cause some problems. Thats why the with method was introduced. But as i mentioned before, there was a minor bug in VSC and a i got it how to do that.

you can read and write this way:

    f=open("note.txt",'w+')
    f.write("is it working still ?")
    f.seek(0)
    content=f.read()
    print (content)
Sign up to request clarification or add additional context in comments.

Comments

0
import sys
import os
import shutil

def leave():
    sys.exit("You are leaving CUI Text Editor")


def read():
    try:
        filename = input("Enter file name: ")
        target = open(filename, "r")
        readfile = target.read()
        print(readfile)
    except Exception as e:
        print("There was a problem: %s" % (e))


def delete():
    filename = input("Enter file name: ")
    try:
        os.unlink(filename)
    except Exception as e:
        print("There was a problem: %s" % (e))


def write():
    try:
        filename = input("Enter file name: ")
        target = open(filename, "a")
        while True:
            append = input()
            target.write(append)
            target.write("\n")
            if append.lower() == "menu":
                break
    except Exception as e:
        print("There was a problem: %s" % (e))


def cwd():
    try:
        print(os.getcwd())
        change = input("Change Y/N: ")
        if change.startswith("y"):
            path = input("New CWD: ")
            os.chdir(path)
    except Exception as e:
        print("There was a problem: %s" % (e))


def rename():
    try:
        filename = input("Enter current file name: ")
        new = input("Enter new file name: ")
        shutil.move(filename, new)
    except Exception as e:
        print("There was a problem: %s" % (e))


while True:
    print("Options: write, read, cwd, exit, delete, rename")
    do = input("So, what are you wishing for today: ")
    if do.lower() == "write":
        write()
    elif do.lower() == "read":
        read()
    elif do.lower() == "delete":
        delete()
    elif do.lower() == "exit":
        leave()
    elif do.lower() == "cwd":
        cwd()
    elif do.lower() == "rename":
        rename()

Have my advice, use r+ mode for safety, and use as many try catch blocks you wish to have. file management in python is easy then c++ streams.

2 Comments

Can you please explain it in simple method. What is the possibly correct way of writing and reading the files in python. I'm currently learning it. I want simple and working method, don't complicate things. I'm just looking for the proper way of doing file handling using simple and basic method.
this is best code to start learning. there are different functions defined for each operation, you need to learn each operation not just read and write.
0
file=open('word.txt','rw+')
file.write("Python you are making me mad")
file.read()

1 Comment

Traceback (most recent call last): File "c:\Users\ishfa\Documents\Python 3 VSC\.vscode\IO.py", line 1, in <module> f=open('note.txt','rw+') ValueError: must have exactly one of create/read/write/append mode
0

Okay, after searching and trying finally i got it. First of all it was a bug in Visual Studio code. You need to use exit() in terminal whenever such case occurs. Second you need to use seek(0) before printing, this way the simple program as i shared will run fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.