텍스트 파일의 URL이 주어지면 텍스트 파일의 내용을 읽는 가장 간단한 방법은 무엇입니까?
Python에서 텍스트 파일의 URL을 지정할 때 텍스트 파일의 로컬 복사본을 저장하지 않고 텍스트 파일의 내용에 액세스하고 파일의 내용을 로컬로 한 줄씩 인쇄하는 가장 간단한 방법은 무엇입니까?
TargetURL=http://www.myhost.com/SomeFile.txt
#read the file
#print first line
#print second line
#etc
2016년 9월 편집: 파이썬 3 이상에서는 urllib2 대신 urllib.request를 사용합니다.
가장 간단한 방법은 다음과 같습니다.
import urllib2 # the lib that handles the url stuff
data = urllib2.urlopen(target_url) # it's a file like object and works just like a file
for line in data: # files are iterable
print line
윌이 제안한 것처럼 "읽기 줄"도 필요하지 않습니다.다음으로 단축할 수도 있습니다.
import urllib2
for line in urllib2.urlopen(target_url):
print line
그러나 Python에서는 가독성이 중요합니다.
그러나 네트워크 프로그래밍을 사용하는 대부분의 경우 예상되는 데이터의 양이 존중될지 여부를 모르기 때문에 이 방법이 가장 간단하지만 안전한 방법은 아닙니다.따라서 일반적으로 예상되는 데이터에 충분하지만 스크립트가 범람하는 것을 방지할 수 있는 고정적이고 합리적인 양의 데이터를 읽는 것이 좋습니다.
import urllib2
data = urllib2.urlopen("http://www.google.com").read(20000) # read only 20 000 chars
data = data.split("\n") # then split it into lines
for line in data:
print line
파이썬 3의 두 번째 예:
import urllib.request # the lib that handles the url stuff
for line in urllib.request.urlopen(target_url):
print(line.decode('utf-8')) #utf-8 or iso8859-1 or whatever the page encoding scheme is
저는 Python의 초보자이며 수락된 솔루션에서 Python 3에 대한 즉석 의견은 혼란스러웠습니다.후세를 위해, 파이썬 3에서 이것을 하기 위한 코드는
import urllib.request
data = urllib.request.urlopen(target_url)
for line in data:
...
또는 그 대신에
from urllib.request import urlopen
data = urlopen(target_url)
참고로 그냥import urllib
작동하지 않습니다.
요청 라이브러리는 인터페이스가 더 단순하며 Python 2와 3 모두에서 작동합니다.
import requests
response = requests.get(target_url)
data = response.text
한 줄 한 줄 읽을 필요가 없습니다.다음과 같은 모든 것을 얻을 수 있습니다.
import urllib
txt = urllib.urlopen(target_url).read()
import urllib2
for line in urllib2.urlopen("http://www.myhost.com/SomeFile.txt"):
print line
Python 3의 또 다른 방법은 urllib3 패키지를 사용하는 것입니다.
import urllib3
http = urllib3.PoolManager()
response = http.request('GET', target_url)
data = response.data.decode('utf-8')
이것은 urllib3가 가지고 있는 것을 자랑하기 때문에 urllib보다 더 나은 옵션이 될 수 있습니다.
- 나사산 안전.
- 연결 풀링입니다.
- 클라이언트 측 SSL/TLS 확인.
- 다중 부분 인코딩을 사용하여 파일을 업로드합니다.
- 요청을 재시도하고 HTTP 리디렉션을 처리하는 도우미입니다.
- gzip 및 deflate 인코딩을 지원합니다.
- HTTP 및 SOCKS에 대한 프록시 지원.
- 100% 테스트 범위.
import urllib2
f = urllib2.urlopen(target_url)
for l in f.readlines():
print l
여기서 Python 2가 Python 3과 함께 작동하도록 @ken-kinder가 제안한 솔루션을 업데이트합니다.
import urllib
urllib.request.urlopen(target_url).read()
저는 위의 답변 중 어떤 것도 직접적으로 효과가 없었습니다.대신에, 저는 다음과 같이 해야 했습니다(파이썬 3).3).
from urllib.request import urlopen
data = urlopen("[your url goes here]").read().decode('utf-8')
# Do what you need to do with the data.
요청 패키지는 @Andrew Mao가 제안한 것처럼 간단한 UI에 매우 잘 작동합니다.
import requests
response = requests.get('http://lib.stat.cmu.edu/datasets/boston')
data = response.text
for i, line in enumerate(data.split('\n')):
print(f'{i} {line}')
o/p:
0 The Boston house-price data of Harrison, D. and Rubinfeld, D.L. 'Hedonic
1 prices and the demand for clean air', J. Environ. Economics & Management,
2 vol.5, 81-102, 1978. Used in Belsley, Kuh & Welsch, 'Regression diagnostics
3 ...', Wiley, 1980. N.B. Various transformations are used in the table on
4 pages 244-261 of the latter.
5
6 Variables in order:
URL에서 데이터 세트/데이터 프레임을 추출하는 방법에 대한 카글 노트북 확인
내 생각엔requests
최선의 선택입니다.또한 인코딩을 수동으로 설정할 수도 있습니다.
import requests
response = requests.get("http://www.gutenberg.org/files/10/10-0.txt")
# response.encoding = "utf-8"
hehe = response.text
간단한 방법론에도 사용할 수 있습니다.
import requests
url_res = requests.get(url= "http://www.myhost.com/SomeFile.txt")
with open(filename + ".txt", "wb") as file:
file.write(url_res.content)
이러한 답변은 Python 3에서 작동하지 않습니다.나는 파이썬 3.9를 사용하고 있으며 적어도 2010년으로 거슬러 올라가는 urllib2의 가져오기를 거부합니다.
다음은 URL이 지정된 원격 서버에 있는 텍스트 파일을 읽는 방법입니다.
import io
import urllib
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
url = 'https://server.com/path/hello world.txt'
req = urllib.request.Request(url, headers=hdr)
u = urllib.request.urlopen(req)
file = io.TextIOWrapper(u, encoding='utf-8')
file_contents = file.read()
print(file_contents)
답을 찾는 것이 매우 어려웠기 때문에 이것이 누군가에게 도움이 되기를 바랍니다.
컨텍스트 관리자 블록을 사용하여 utf-8을 사용하여 URL을 읽고 디코딩할 수 있습니다.
import urllib.request
# Sample URL text file:
url = "https://example-files.online-convert.com/document/txt/example.txt"
with urllib.request.urlopen(url) as fin:
# Save locally if desired.
text = fin.read().decode("utf-8")
# Or just print out each line per OP request.
for line in fin.readlines():
print(line.decode('utf-8').strip())
언급URL : https://stackoverflow.com/questions/1393324/given-a-url-to-a-text-file-what-is-the-simplest-way-to-read-the-contents-of-the
'programing' 카테고리의 다른 글
UICollectionViewCell 내부의 UICollectionView -- 동적 높이? (0) | 2023.06.10 |
---|---|
PL/SQL에서 CASE 문을 실행하는 동안 ORA-06592: CASE를 찾을 수 없는 이유는 무엇입니까? (0) | 2023.06.10 |
파이어베이스에서 데이터를 구성하는 가장 좋은 방법은 무엇입니까? (0) | 2023.06.10 |
vuex, vue-router, pinia 등에 액세스하는 방법SSR 친화적인 방식으로 Vue 구성 요소 외부에? (0) | 2023.06.10 |
Firebase 데이터를 Java 개체로 변환하는 방법...? (0) | 2023.06.10 |