当前位置: 代码迷 >> python >> 如何在Python中创建文件,读写文件? 写作 用于阅读
  详细解决方案

如何在Python中创建文件,读写文件? 写作 用于阅读

热度:37   发布时间:2023-07-14 08:43:53.0

我能找到的所有教程都遵循相同的格式,但是没有工作。我没有得到错误信息,但我得不到正常的输出。 我得到的似乎是某个内存位置的文件描述。

#file_test

ftpr= open("file","w")
ftpr.write("This is a sample line/n")
a=open("file","r")
print a




#This is the result

<open file 'file', mode 'r' at 0x00000000029DDDB0>
>>> 

你想阅读文件的内容吗? 尝试print a.readlines()

即:

with open('file', 'w') as f:
  f.write("Hello, world!\nGoodbye, world!\n")

with open('file', 'r') as f:
  print f.readlines()  # ["Hello, world!\n", "Goodbye, world!\n"]

仅供参考, ,如果你不熟悉他们,确保open() -d文件close() -d。

这不是读取文件的正确方法。 您正在打开作为文件类型对象的打开调用的返回值。 这样做是为了阅读和写作。

写作

F =打开( “MYFILE”, “W”)

f.write( “你好\\ n” 个)

f.write(“这是一个样本行/ n”)

f.close()

用于阅读

F =打开( “文件”, “R”)

string = f.read()

打印(“字符串”)

f.close()

  相关解决方案