簡體   English   中英

用變量在python中打開和讀取文件

[英]opening and reading file in python with variable

我的代碼:

#!/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!");
}

我嘗試將文件讀入變量,然后將其打印輸出。

} printf("Hello World!");

我知道這可能是一些愚蠢的錯誤(我是初學者)..為什么它不能打印所有文件? 你能幫我嗎?

由於兩個“}”和“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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM