पायथन 3.5 के लिए फ़ाइलों का डिफ़ॉल्ट एन्कोडिंग 'utf-8' है।
विंडोज के लिए फ़ाइलों का डिफ़ॉल्ट एन्कोडिंग कुछ और होता है।
आप दो पाठ फ़ाइलों को खोलने का इरादा है, तो आप इस कोशिश कर सकते हैं:
import locale
locale.getdefaultlocale()
file1 = input("Enter the name of the first file: ")
file1_open = open(file1, encoding=locale.getdefaultlocale()[1])
file1_content = file1_open.read()
मानक पुस्तकालय में कुछ स्वचालित पहचान होनी चाहिए।
नहीं तो आप अपना खुद का बना हो सकता है:
def guess_encoding(csv_file):
"""guess the encoding of the given file"""
import io
import locale
with io.open(csv_file, "rb") as f:
data = f.read(5)
if data.startswith(b"\xEF\xBB\xBF"): # UTF-8 with a "BOM"
return "utf-8-sig"
elif data.startswith(b"\xFF\xFE") or data.startswith(b"\xFE\xFF"):
return "utf-16"
else: # in Windows, guessing utf-8 doesn't work, so we have to try
try:
with io.open(csv_file, encoding="utf-8") as f:
preview = f.read(222222)
return "utf-8"
except:
return locale.getdefaultlocale()[1]
और फिर
file1 = input("Enter the name of the first file: ")
file1_open = open(file1, encoding=guess_encoding(file1))
file1_content = file1_open.read()
फ़ाइलें कहां से आ रहे हैं? –
मेरे शिक्षक ने प्रोग्राम चलाने के दौरान उपयोग किए जाने वाले परीक्षक फ़ाइलों को जोड़ा। टेस्टर्स में से एक में पहली फ़ाइल जो मुझे त्रुटि देती है वह है "टेस्ट/4-test.txt" – Erica
आपके पास स्ट्रिंग में एम्बेडेड एक शून्य बाइट है जो पायथन का उपयोग करके काम नहीं करेगा, आपको नल बाइट्स/एस को हटाने की जरूरत है । आप कौन सा ओएस उपयोग कर रहे हैं? –