如何解决Python 3中的文件处理问题 [英] How to Fix File Handling Issues in Python 3

查看:86
本文介绍了如何解决Python 3中的文件处理问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习python3.我正在经历文件处理的练习.我的代码有问题,当我尝试编写文件时,有时不生成任何文件,有时会生成文件,但是当我尝试读取文件时.它显示空白输出.在大多数情况下,当我使用基础知识和简单代码时,它会给出某种语法错误.但是有时我没有使用在终端上运行,而是在单击运行代码时产生了输出,但仍然在终端上给出了错误.

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.

我尝试使用With和休闲方法来做到这一点.我已经在Google上查找了该问题,但没有任何具体答案.我尝试遵循python文档及其代码.

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())
```

也尝试过这种方式:

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

推荐答案

呵呵,它相当简单...每当您以写入格式打开文件时,都只能对其进行写入,因此要读取该文件,您需要先将其关闭,然后再以读取格式将其重新打开.

Hehe, its rather simple... whenever you open a file in a write format, you can only write to it, so to read it you need to close it and then reopen it as a read format.

示例:

file=open("Example.txt","w")
file.write("Some text")
file.close()
file=open("Example.txt","r")
text=file.read()
print(text)
file.close()

这篇关于如何解决Python 3中的文件处理问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆