使用变量在python中打开和读取文件
我的代码:使用变量在python中打开和读取文件,python,macos,file,Python,Macos,File,我的代码: #!/usr/bin/python3 import getopt import sys import re def readfile(): with open("hello.c", "r") as myfile: data=myfile.read() print data readfile() 在hello.c文件中: #include <stdio.h> void main() { auto print
#!/usr/bin/python3
import getopt
import sys
import re
def readfile():
with open("hello.c", "r") as myfile:
data=myfile.read()
print data
readfile()
在hello.c文件中:
#include <stdio.h>
void main()
{
auto
printf("Hello World!");
}
#包括
void main()
{
汽车
printf(“你好,世界!”);
}
我试着把文件读入变量,然后打印出来。。。
它写道:
printf(“你好,世界!”)代码>
我知道这可能是一些愚蠢的错误(我是初学者)…为什么它不打印所有文件?你能帮忙吗?既然“}”和“printf”都打印出来了,我觉得整个文件都在打印,但都在一行上-光标只是返回到当前行的开头,并用新数据覆盖旧数据
如果文件中的所有行都以回车结束,而不是换行,则可能发生这种情况。最简单的解决方案是使用replace
将新行放在它们所属的位置
#!/usr/bin/python3
import getopt
import sys
import re
def readfile():
with open("hello.c", "r") as myfile:
data=myfile.read().replace("\r", "\n")
print data
readfile()
您也可以在通用换行符模式下打开该文件,该模式将\r\n转换为您所需的格式。但这种行为已被弃用,并将在Python 4.0中消失
#!/usr/bin/python3
import getopt
import sys
import re
def readfile():
with open("hello.c", "Ur") as myfile:
data=myfile.read()
print data
readfile()
我只是复制粘贴了两个来源,工作得很好。但是Python2.7。你的控制台工作正常吗?也许是和蟒蛇3有关的。。。但是我怀疑控制台可以
打印(repr(data))
来查看文件中的内容。@Kevin谢谢你,这正是我想要的…但是有没有可能编辑该文件的每一行(例如,为了正则表达式匹配,用子字符串替换)?如果你问“如何逐行迭代文件?”,然后对文件中的行执行:
或lines=file.readlines()
。如果您询问“如何对文件进行更改?”,则需要将文件读入字符串或列表,对该对象进行更改,然后在“w”模式下再次打开文件并将数据写回。